[GIS] Highlight L.divIcon on mouseover or programmatically in Leaflet map

javascriptleafletmarkers

I want to highlight L.divIcon svg markers on mouseover and/or from an "outside action" like pressing a button.

here is a simplified testcase https://jsfiddle.net/sxvLykkt/5/

Markers are generated dynamically (geoJson originally) and added to a L.FeatureGroup().
On mouseover I set a bigger version of the icon (divIconActive) on a temporary layer, that I remove on mouseout. Unfortunately this doesn't work as indented (it's flickering on mouseover, the event is firing mouseover and mouseout I believe). How can I solve this?

And how can I access the markers when clicking one of the buttons? Somehow over their index I believe?! I can't wrap my head around.

Here is a portion of the code how the markers are created:

// init map and tileLayer -> jsfiddle
var coords = [[53, 13],[49, 10],[46, 12],[51, 16]];

$.each(coords, function(i,e){
  // create the button
  $('#controls').append('<button>'+i+'</button>')

  var marker = L.marker(e, {
    icon: divIcon,
    id: i
  });

  locationLayer.addLayer(marker);

  marker.on('mouseover', function(e){
    markerTemp = L.marker(e.latlng, {
        icon: divIconActive
    }).addTo(map);

  });

  marker.on('mouseout', function(e){
    markerTemp.remove();
  });

});

locationLayer.addTo(map);

$('button').on('click', function(e){
    alert('Highlight the right marker!')
});

PS: this is a cross post from Stackoverflow.

Edit: JsFiddle https://jsfiddle.net/sxvLykkt/12/ with the proposed, working solution by TomazicM

Best Answer

Below is one possible solution. It's not the most elegant but it works. Instead of additional layer setIcon method is used for setting active icon. Function setTimeout is used beacuse I couldn't get it work otherwise.

var coords = [[53, 13],[49, 10],[46, 12],[51, 16],[52, 12]];
var markerArray = [];
var iMarker = -1;

function setActiveIcon(marker) {
  marker.setIcon(divIconActive);
};

$.each(coords, function(i,e){
  // create the button
  $('#controls').append('<button>'+i+'</button>')

  var marker = L.marker(e, {
    icon: divIcon,
    id: i
  });

  locationLayer.addLayer(marker);

  marker.on('mouseover', function(e){
    if (iMarker == i) return;
    setTimeout(setActiveIcon, 10, this);
    if (iMarker >= 0) markerArray[iMarker].setIcon(divIcon);
    iMarker = i;
  });

  marker.on('mouseout', function(e){
    this.setIcon(divIcon);
    iMarker = -1;
  });

  markerArray[i] = marker;
});

locationLayer.addTo(map);

$('button').on('click', function(e){
  if (iMarker >= 0) markerArray[iMarker].setIcon(divIcon);
  markerArray[this.innerText].setIcon(divIconActive);
  iMarker = this.innerText;
});