【发布时间】: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