1

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();
    });
}

2 Answers 2

0

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
  });
}
2
  • The same problem occurs unfortunately. The problem is the setIcon function, which this person also asked about: stackoverflow.com/questions/37408445/leaflet-mo. I've yet to find a solution
    – saoirse
    Apr 26, 2019 at 22:13
  • 1
    Can you then add icon definition code to your question?
    – TomazicM
    Apr 27, 2019 at 8:23
0

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();
        }
    );
} 

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .