1

I have a list of links and withing the links I have data attributes for lat and lon.

<a href="#" data-lat="23.232322" data-lon="-97.2466634">
<a href="#" data-lat="23.333452" data-lon="-97.2234234">

When I hover over the links I would like to show marker on the map.

let loc = document.querySelectorAll("a[data-lat]");
                            
loc.forEach(node => {
    node.addEventListener("mouseover", locOver);
    node.addEventListener("mouseout", locOut);
})
                            
function locOver(event) {
    var llt = event.target.dataset["lat"],
        lln = event.target.dataset["lon"];
                                    
    L.marker([llt, lln]).addTo(map); 
}
                      
function locOut(event) {
   //remove markers associated with the links                          
}

This seems to work partially but I need to figure out how to resolve a few issues: Currently every time I hover over the same link it keeps adding more and more markers. I was thinking of removing the marker on mouseout event but later I found a function (setLatLng) that probably is more efficient and instead of adding and removing just uses the same marker to just change it's coordinates.

Also, when I am no longer hovering over links I'd like to remove the last link's marker. I do have a marker of my current position that I'd like to keep on the map.

I've tried it in many different ways but always get JS errors in console and all my solutions seem to be over-complicating the issue. I'm certain I'm pretty close, just stuck.

3
  • 1
    Welcome to GIS SE. As a new user, please take the Tour, which emphasizes the importance of asking One question per Question. Instead of providing code that doesn't try to work and two questions, please Edit the Question to make the attempt at the first issue and report the actual errors encountered.
    – Vince
    Feb 14, 2021 at 20:45
  • 1
    Wow, harsh... What prompted -1 here?
    – santa
    Feb 14, 2021 at 21:38
  • Probably your initial question, where at first sight it looked like you have two questions, but in reality it was a single one (at least in my opinion).
    – TomazicM
    Feb 15, 2021 at 9:24

1 Answer 1

3

Quick and 'dirty' solution would be to simply create global var marker for saving created marker, which can then be remove upon mouse exit:

var marker;

function locOver(event) {
    var llt = event.target.dataset["lat"],
        lln = event.target.dataset["lon"];
                                    
  marker = L.marker([llt, lln]).addTo(map); 
}
                      
function locOut(event) {
  marker.remove();
}

I call this solution 'dirty' because it creates a new marker each time mouse is over the same link. Correct solution would be associate a unique id with each link and then create marker only the first time, and later retrieve created marker with the help of this id.

Solution with id would go like this:

  1. When attaching event handlers to link, also add unique id to the element.
  2. Create an array to save markers, where index will be id of the link.
  3. When mouse gets over link, first check if marker already exists. If it exists, add it to the map. If it doesn't exist, create it, save to marker array and add it to the map.
  4. When mouse leaves the link, get marker from the array of markers, using id as index, and remove marker from the map.

Code could then look something like this (ES5):

var i = 0;
loc.forEach(function(node) {
    node.addEventListener("mouseover", locOver);
    node.addEventListener("mouseout", locOut);
    node.id = i++;
});
                            
var markers = [];

function locOver(event) {
  var target = event.target;
  if (markers[target.id]) {
    markers[target.id].addTo(map);
    }
  else {
    var llt = target.dataset["lat"];
    var lln = target.dataset["lon"];
    marker = L.marker([llt, lln]).addTo(map); 
    markers[target.id] = marker;
  }
}
                      
function locOut(event) {
  markers[event.target.id].remove();
}
5
  • Thanks! I looked around for a way to add an ID but I was surprised that you can add all sorts of optional attributes except for ID...
    – santa
    Feb 14, 2021 at 20:49
  • So are you satisfied with the solution or you would like to have more sophisticated one with id?
    – TomazicM
    Feb 14, 2021 at 20:52
  • Your solution definitely works.If there's a better one I'd be happy to have it. While testing now I noticed that my code only works when my mouse hovers over the link, however, there are couple div containers withing it, and when the mouse moves over those the marker disappears, which is weird to me since it's still linked. I tried moving my other code to look for nodes in ...("a[data-lat] div") but it just stops working. Trying to figure out a stable and not glitchy way of showing markers. But I think it's a separate question.
    – santa
    Feb 14, 2021 at 21:13
  • Added solution with id. Problem with div element within link is pure HTML problem, so you should ask for solution on StackOverflow site.
    – TomazicM
    Feb 14, 2021 at 21:24
  • Ohh, this is nice. I much rather work with IDs, in case I decide to enhance functionality later. Thanks a bunch! I have posted the other question on stack overflow. Because when I hover over div and loose lat lon from the link I instantly get JS errors. Also I will poke around Leaflet's docs to see if there's a way to slowly fade out the marker, since it looks a bit jerky when I move my mouse over the list now. If it doesn't exist, I'm sure I can come up with some CSS magic. Cheers!
    – santa
    Feb 14, 2021 at 21:37

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.