我正在尝试将本地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中所说的做法,这是更好的做法吗?
答案 0 :(得分: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);