0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.