【问题标题】:Trouble binding events/popups to existing leaflet geojson layer无法将事件/弹出窗口绑定到现有的传单 geojson 层
【发布时间】:2014-06-05 16:56:35
【问题描述】:

我正在尝试将本地 json 数据添加到 Leaflet 中的 GeoJson 层,然后(目前)将弹出窗口绑定到 json 中的每个功能。问题是我无法先创建 geojson 图层,然后再绑定弹出窗口。有没有办法做到这一点?我只能同时创建图层并添加弹出窗口。到目前为止我所拥有的:

创建地图。

map = new L.Map('map');

抓取本地json文件:

{
"type": "FeatureCollection",
"features": [
    {
        "type": "Feature",
        "properties": {
            "name": "Denver",
            "amenity": "Baseball Stadium",
            "popupContent": "This is where the Rockies play!"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-102.99404, 37.75621]
        }
    },
    {
        "type": "Feature",
        "properties": {
            "name": "Baltimore",
            "amenity": "Baseball Stadium",
            "popupContent": "This is where the Orioles play!"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [-76.6167, 39.2833]
        }
    }
    ]
}

并将 json 发送到 plotData():

function plotData( data ) 
{
  var pointLayer = L.geoJson().addTo(map);

  // 1. works
  L.geoJson(data, {
    onEachFeature: onEachFeature
  }).addTo(map);


  // 2. does not bind popups
  pointLayer.addData( data, {
    onEachFeature: onEachFeature
      }
  );

  // 3. Error - invalid GeoJson Object
  pointLayer.addData( L.geoJson(data, {
    onEachFeature: onEachFeature
      })
  );
}

function onEachFeature( feature, layer ) 
{
  layer.bindPopup( feature.properties.name );
}

场景 1 和 2 的标记在地图上显示得很好(其中 1 也显示弹出窗口)。现在,有什么理由我不应该尝试先创建图层然后将操作绑定到功能?只做我在 1 中所说的更好的做法吗?

【问题讨论】:

    标签: json popup leaflet layer geojson


    【解决方案1】:

    第三个选项不起作用,因为您将 L.Layer 对象提供给 GeoJSON 对象应该去的地方。 L.GeoJSON.addData() 函数没有 onEachFeature 参数。基本上,当您处理完 GeoJSON 后,它的特征属性就消失了。

    有两种方法可以继续。

    // create empty GeoJSON layer
    var pointLayer = L.geoJson(null, { onEachFeature: storeName }).addTo(map);
    // add data to it later, invoking storeName() function
    pointLayer.addData(data);
    // which stores names
    function storeName(f, l) { l._gname = f.properties.name; }
    // and when you're ready...
    pointLayer.eachLayer(addPopupFromGName);
    // add popups with stored name
    function addPopupFromGName(l) { l.bindPopup(l._gname); }
    

    或者只是将 onEachFeature 函数添加到 L.GeoJSON 层选项:

    var pointLayer = L.geoJson(null, { onEachFeature: onEachFeature }).addTo(map);
    

    【讨论】:

    • 感谢您的回复!我在发布后几个小时就想通了,但由于我的代表率低,我无法这么快回答我自己的问题:(,但我的解决方案和你的一样。
    猜你喜欢
    • 2022-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多