问题
Working in leaflet-0.7.3, I have built custom popups using properties of geoJson data using layer.bindPopup in onEachFeature. However I am also attempting to use layer._leaflet_id = feature.properties.fid in onEachFeature in order to make use of a function to move between features with an external control.
This function (clickOnMapItem in the below code extract) works, and I'm intending to make use of it with NEXT and PREVIOUS buttons outside of the map.
However after the inclusion of layer._leaflet_id = feature.properties.fid in onEachFeature the pop ups no longer appear. How can I perform both tasks successfully inside onEachFeature?
I've included a code extract below.
function onEachFeature(feature, layer) {
layer.bindPopup('<b>Location: </b>' + feature.properties.name);
layer.on({
click: getName
});
//including this next line seems to prevent the popups
layer._leaflet_id = feature.properties.fid;
}
function clickOnMapItem(itemId) {
var id = parseInt(itemId);
//get target layer by it's id
var layer = geojson.getLayer(id);
//fire event 'click' on target layer
layer.fireEvent('click');
}
function getName(e) {
//info.update is a function used to populate an external div
info.update(e.target.feature.properties);
}
回答1:
DO NOT use _leaflet_id
It's internal to leaflet and you won't find any documentation about it.
For what you want to achieve, I would not use fireEvent('click') to open a popup. There is a method openpopup for that.
回答2:
The exact cause of the issue with layer._leaflet_id = feature.properties.fid; remains unknown (as YaFred points out, it's internal to Leaflet and therefore has no supporting documentation), but I did discover an alternative solution that I hope will help others.
Instead of layer._leaflet_id = feature.properties.fid;, I used layers[feature.properties.fid] = layer;, having previously called var layers = {};, based on this answer. I've included the updated code extract, which builds Next and Previous functionality that can be used to scroll through the layer.
var currentPhoto;
var layers = {};
function onEachFeature(feature, layer) {
layer.bindPopup('<b>Location: </b>' + feature.properties.name);
layer.on(
"click",function(e){getName(e);
currentPhoto = parseInt(layer.feature.properties.fid);
});
layers[feature.properties.fid] = layer;
}
// call from outside map
function highlightFeature(fid){
layers[fid].fireEvent('click');
}
$('#prev').click(function() {
highlightFeature(currentPhoto-1);
});
$('#next').click(function() {
highlightFeature(currentPhoto+1);
});
function getName(e) {
//info.update is a function used to populate an external div
info.update(e.target.feature.properties);
}
来源:https://stackoverflow.com/questions/54504884/layer-popups-prevented-by-additional-code-in-oneachfeature