1
votes

I've never worked with JavaScript before. I'm trying to create a map where different layers can be hidden per users preference. I came across the helpful example on map box showing the exact code at https://www.mapbox.com/mapbox-gl-js/example/toggle-layers/.

Now, my problem is, because I have numerous point layers of different magnitudes, I was forced to create several layers and filter them based on the desired attribute so each points appearance reflects that specific magnitude. However, I want all these points to be organized into years, so I grouped the layers. So all my layer names look something like this (2006_mag2,2006_mag8,2010_mag3...).

However, I want the hide/show option to show layers based on years. So I was thinking I could do some sort of operator like we use in sql (i.e. '2006%' or a LIKE operator). Looking at some posts a lot of people use '*' in JavaScript? So this is what it would look like for each layer individually before:

var toggleableLayerIds = [ '2006_mag2', '2010_mag3' ];

for (var i = 0; i < toggleableLayerIds.length; i++) {
    var id = toggleableLayerIds[i];
}

and this is my botched attempt at trying to group a number of the layers together:

var toggleableLayerIds = [ '2006.*', '2008.*' ];

for (var i = 0; i < toggleableLayerIds.length; i++) {
    var id = toggleableLayerIds[i];
}

Any guidance you guys can provide will be greatly appreciated.

1

1 Answers

0
votes

You could try to use loops with regex to group layerIds by date. Sorry I changed the name of your variables. This will get you an object with layerIds grouped by date.

    var layerIds = [ '2006_mag2', '2010_mag3', '2006_mag8', '2006_mag1', '2008_mag2'];
    var dates = ['2006', '2010'];
    var groupedLayers = {};

    //init your object to have a member for each date
    //this could be done inside the loops below by testing if the array exists before pushing the matching layerId
    for (var i=0; i < dates.length; i++) {
      groupedLayers[dates[i]] = [];
    }
    
    //loop over your layerIds to match with the RegExp
    for (var i=0; i < layerIds .length; i++) {
        for (var j=0; j < dates.length; j++) {
            var searchPattern = new RegExp('^' + dates[j]);
            if (searchPattern.test(layerIds[i])) {
                groupedLayers[dates[j]].push(layerIds[i]);
            }
         }
    }

    console.log(groupedLayers)

Please tell me what exact result you need so I could help you more.