Geographic Information Systems Asked by saoirse on February 25, 2021
I’m initializing GeoJSON markers in Leaflet, and I’m trying to change the color and open a label on mouseover. Upon mouseout, I want to change back to the default color and close the label. However, the layer only handles one event listener — in the code below, only the mouseover event is fired. When the mouseover listener is commented out, only then will the mouseout event be active. What am I missing in my code to handle more than one listener?
// load geojson data with default variables shown
var mapLayer = L.geoJSON(data[0]['features'], {
pointToLayer: function (feature, latlng) {
var marker = L.marker(latlng, {icon: defaultMarker});
return marker;
},
onEachFeature: onEachFeature
}).addTo(map);
// on each marker, do the following
function onEachFeature(feature,layer) {
layer.bindTooltip(feature.properties.label);
layer.on('mouseover', function(e){
layer.setIcon(highlightMarker);
layer.openTooltip();
});
layer.on('mouseout', function(e){
console.log("mouseout");
layer.setIcon(defaultMarker);
layer.closeTooltip();
});
}
Just add both listeners in one call (see Leaflet example https://leafletjs.com/examples/choropleth/example.html):
function showTooltip(e) {
e.target.setIcon(highlightMarker);
e.target.openTooltip();
}
function hideTooltip(e) {
e.target.setIcon(defaultMarker);
e.target.closeTooltip();
}
function onEachFeature(feature,layer) {
layer.bindTooltip(feature.properties.label);
layer.on({
mouseover: showTooltip,
mouseout: hideTooltip
});
}
Answered by TomazicM on February 25, 2021
Your code is trying to create layer.on
twice, this is why mouseover
is not fired.
You can use anonymous functions like this:
function onEachFeature(feature,layer) {
layer.bindTooltip(feature.properties.label);
layer.on(
'mouseover': function(e){
layer.setIcon(highlightMarker);
layer.openTooltip();
},
'mouseout': function(e){
console.log("mouseout");
layer.setIcon(defaultMarker);
layer.closeTooltip();
}
);
}
Answered by NettaB on February 25, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP