无法将事件/弹出窗口绑定到现有的传单geojson图层

问题描述 投票:2回答:1

我试图将本地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个回答
1
投票

第三个选项不起作用,因为你正在为GeoJSON对象提供L.Layer对象。 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);
© www.soinside.com 2019 - 2024. All rights reserved.