Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two geoJSON feature collections in to two layer groups

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?

like image 986
thusithak Avatar asked Dec 20 '22 06:12

thusithak


1 Answers

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

like image 112
iH8 Avatar answered Dec 28 '22 08:12

iH8