Search code examples
javascriptleafletopenstreetmap

Show map markers on hover


I have a list of links to several locations. I would like to add map marker to my OSM map and remove it when I hover out, while adding new one I hover over etc. I've been been able to add marker to the map on hover but I'm not able to remove them.

HTML

<a href="/..." onmouseover="mkron(this)" onmouseout="mkroff()">...</a>

JS

function mkron(x) {
   // some code to get lat lon 
   L.marker([lat, lon]).addTo(map);
}

function mkroff() {
    markers.clearLayers();
}

What am I missing?


Solution

  • Your problem is that you add the marker directly to the map instead of adding it to the LayerGroup / FeatureGroup markers.

    I don't know the rest of your code but it should look like that:

    var markers = L.featureGroup().addTo(map);
    
    function mkron(x) {
       // some code to get lat lon 
       L.marker([lat, lon]).addTo(markers);
    }
    
    function mkroff() {
        markers.clearLayers();
    }
    

    The other variant would be to store the layer in a global variable and then remove it from the map:

    var marker;
    
    function mkron(x) {
       // some code to get lat lon 
       marker = L.marker([lat, lon]).addTo(map);
    }
    
    function mkroff() {
      if(marker){
        map.removeLayer(marker)
        marker = null;
      }
    }