1

If I create a shapefile layer

var ac_shpfile = new L.Shapefile("data/AC.zip", {onEachFeature: function (feature, layer) {
/* Add some colors based on shapefile features */
}});

and then add it to the map I've created

ac_shpfile.addTo(map);

How do I later remove that shapefile layer from the map? I plan to create another shapefile layer (same shapefile but with different colorings) and based on some user action switch between these two shapefile layers being shown. How do I add/remove shapefile layers like this? I've looked for the "opposite" of addTo() in the documentation but this doesn't seem tot be easy to find?

  • typically it would be map.removeLayer(shapefile) but it depends on whether the shapefile plugin supports that api – toms Aug 4 '15 at 18:59
  • Ok, thanks! It does seem that the shapefile plugin supports this, and I am getting the effect that I wanted. If you post your response as an answer I will accept it. – sail0r Aug 4 '15 at 20:31
1

It looks like the Leaflet Shapefile plugin has implemented L.Shapefile as an extension of L.GeoJson. L.GeoJson implements the ILayer interface, including the method removeLayer()

Long way of saying that this should work:

map.removeLayer(shapefile)
0

Check out this example.

Based on your code snippet, you can do something like this:

var ac_shpfile = new L.Shapefile("data/AC.zip", {onEachFeature: function (feature, layer) {
    /* Add some colors based on shapefile features */
    }});

var baseMaps = {
    //"example title": example_layer
};

var overlayMaps = {
    "AC Shapefile": ac_shpfile
};

L.control.layers(baseMaps, overlayMaps).addTo(map);

That will give you a toggleable layer control.

Otherwise do it in code, as noted above:

ac_shpfile.addTo(map);
map.removeLayer(ac_shpfile)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.