从Leaflet的event.layer.toGeoJSON()获取功能时缺少功能信息

时间:2015-01-21 16:46:41

标签: leaflet geojson

我使用L.geoJson并在我的地图中添加图层,然后使用items.on('点击',功能(事件){})显示所存储的所选对象的信息event.layer(使用toGeoJSON()获取信息。)

问题是,当有一些项目时,一切似乎都有效,但现在当有> 1000个多边形时,使用时的一些数据('点击')不包含我的event.layer中的功能信息。

可能有什么问题?

附加信息:

我们的GeoJSON看起来像这样,它有ID和各种属性等附加数据。

{
"type": "FeatureCollection",
"features": [
  {
    "type": "Feature",
    "id": 1,
    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
    "properties": {"prop1": "value1"}
  },
  {
    "type": "Feature",
    "id": 2,
    "geometry": {"type": "Point", "coordinates": [142.0, 15.5]},
    "properties": {"prop1": "value2"}
  }
 ]
 }

我把所有东西放在地图上:

data = L.geoJson(data);
allItems.clearLayers().addLayer(data);

功能会显示在地图上。

然后我会听取地图上功能的点击次数:

allItems.on('click', function (event) {
    // On many of the features this is empty,
    // on some data can be retrieved.
    // On some that doesn't have ID, properties
    // are empty too
    console.log(event.layer.toGeoJSON().id);
});

已经检查过GeoJSON,ID和属性都在那里。

1 个答案:

答案 0 :(得分:0)

以下是关于如何处理L.GeoJSON图层上的点击事件和/或其功能的一点解释。我已经对代码进行了评论,以解释发生了什么,并为您添加了一个关于Plunker的示例,以便您可以测试该概念。

关于Plunker的示例:http://plnkr.co/edit/TcyDGH?p=preview

代码:

var geoJsonLayer = L.geoJson(data, {
  // Executes on each feature in the dataset
  onEachFeature: function (featureData, featureLayer) {
    // featureData contains the actual feature object
    // featureLayer contains the indivual layer instance
    featureLayer.on('click', function () {
      // Fires on click of single feature
      console.log('Clicked feature layer ID: ' + featureData.id);
    });
  }
}).on('click', function () {
    // Fires on each feature in the layer
    console.log('Clicked GeoJSON layer');
});

至于你的代码,我对allItems的来源感到很困惑。一个layerGroup或类似的东西?试图捕获该对象上GeoJSON层中各个特征的点击不会起作用,因为它无法区分这些特征。对于GeoJSON图层上的处理程序也是如此,它会触发,但不知道您单击了哪个功能。 onEachFeature函数中的处理程序将。但是,如果您理解上面的代码/示例,我现在假设您已经明白了。