Search code examples
mapboxgeojson

How to add Layer stored as variable to mapbox map


I am working with mapbox.js and I am trying to reset a layer that I removed, but stored in a variable. I have created a map object and attached it to a div and stored it as the variable map. I initialize the layers like so

var myLayer = L.mapbox.featureLayer().addTo(map);
var secondLayer = L.mapbox.featureLayer().addTo(map);

Then I store them in a json object

    var geoJsons = {"myLayer": myLayer,
                    "secondLayer": secondLayer
                    };

in a function below, I have an onclick function which draws on the data attribute of the object clicked to point to the specific layer in the json object.

var layer = $(this).data('layer');
map.removeLayer(geoJsons[layer]);

I then try to re-add it on the click of a different button

geoJsons[layer] = L.mapbox.featureLayer().addTo(map);

This last bit does not work. My question is, is there a way to re-add the layer to the map by calling it from within this json object?


Solution

  • geoJsons[layer] = L.mapbox.featureLayer().addTo(map);
    

    What you are doing here is overwriting the layerobject stored with a new instance of L.mapbox.featureLayer. The stored layer is accessible via geoJsons[layer] (Assuming the layer variable holds the string myLayer or secondLayer) you can add it by simply calling it's addTo method like so:

    geoJsons[layer].addTo(map);
    //or 
    map.addLayer(geoJsons[layer]);