问题
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?
回答1:
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
回答2:
Since you create a layer when loading a GeoJSON, you can add it to the layer control as an Overlay Layer (simply modify that example and replace the cities layer.
来源:https://stackoverflow.com/questions/28534705/how-to-add-two-geojson-feature-collections-in-to-two-layer-groups