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

此生再无相见时 提交于 2019-12-19 03:40:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!