[GIS] Changing Color and Opening Label on Hover

geojsonjavascriptleaflet

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

Best Answer

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