I have two geoJSON feature collections that I need to add to the map, and I also want them to be toggled on and off via the layer visibility controllers as shown in http://leafletjs.com/examples/layers-control.html
how can I do this?
There is also a very good tutorial on the usage of L.GeoJSON
, Leaflet's GeoJSON layer, which can be found here: http://leafletjs.com/examples/geojson.html and here is the reference for L.GeoJSON
: http://leafletjs.com/reference.html#geojson You already found the tutorial on L.control.layers
, here is the reference for it: http://leafletjs.com/reference.html#control-layers
It's actually quite simple to do, it's just a matter of creating a layercontrol, loading a GeoJSON file into your script by using your favorite XHR library, use the retrieved data to defined a L.GeoJSON
layer and add it to the layercontrol. In code:
// Create the layercontrol and add it to the map
var controlLayers = L.control.layers().addTo(map);
// Loading a GeoJSON file (using jQuery's $.getJSON)
$.getJSON('/my-folder/my-file.json', function (data) {
// Use the data to create a GeoJSON layer and add it to the map
var geojsonLayer = L.geoJson(data).addTo(map);
// Add the geojson layer to the layercontrol
controlLayers.addOverlay(geojsonLayer, 'My GeoJSON layer title');
});
A working example on Plunker: http://plnkr.co/edit/tFVrrq?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With