如何将两个 geoJSON 特征集合添加到两个图层组中

2022-01-12 00:00:00 openstreetmap leaflet javascript

我有两个 geoJSON 功能集合需要添加到地图中,我还希望通过图层可见性控制器打开和关闭它们,如 http://leafletjs.com/examples/layers-control.html

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

我该怎么做?

推荐答案

Leaflet的GeoJSON层L.GeoJSON的使用也有一个很好的教程,可以在这里找到:http://leafletjs.com/examples/geojson.html 这里是 的参考L.GeoJSON:http://leafletjs.com/reference.html#geojson您已经在 L.control.layers 上找到了教程,这里是它的参考:http://leafletjs.com/reference.html#control-layers

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

其实做起来很简单,只需要创建一个layercontrol,使用你喜欢的XHR库加载一个GeoJSON文件到你的脚本中,使用检索到的数据来定义一个L.GeoJSON图层并将其添加到图层控件.在代码中:

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');

});

关于 Plunker 的工作示例:http://plnkr.co/edit/tFVrrq?p=预览

A working example on Plunker: http://plnkr.co/edit/tFVrrq?p=preview

相关文章