将事件/弹出窗口绑定到现有传单geojson层时出现问题

将事件/弹出窗口绑定到现有传单geojson层时出现问题,json,popup,leaflet,layer,geojson,Json,Popup,Leaflet,Layer,Geojson,我试图将本地json数据添加到传单中的GeoJson层,然后(现在)将弹出窗口绑定到json中的每个特性。问题是我无法先创建geojson层,然后再绑定弹出窗口。有没有办法做到这一点?我只能同时创建图层和添加弹出窗口。到目前为止,我所拥有的: 创建地图 map = new L.Map('map'); 获取本地json文件: { "type": "FeatureCollection", "features": [ { "type": "Feature",

我试图将本地json数据添加到传单中的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]
        }
    }
    ]
}
并通过plotData()发送json:


场景1和场景2的标记在地图上显示得很好(场景1也显示弹出窗口)。现在,有什么理由我不应该先创建图层,然后再将动作绑定到特征上?按照我在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);

谢谢你的回复!我在发帖几小时后就想出来了,但由于我的代表率低,所以没能很快回答我自己的问题:(,但我的解决方案和你的一样。
var pointLayer = L.geoJson(null, { onEachFeature: onEachFeature }).addTo(map);