I have some markers that I load it from a database, but the problem is when I hover on a marker I should change the icon, I can successfully do this, but if I hover on another marker, the first clicked marker is having the icon changed and the on that I hovered remained the same.
Any ideas what can I do?
function addScoala1() {
var scoala = JSON.parse('<?php echo json_encode($scoala) ?>');
for (var i = 0; i < scoala.length; i++) {
var greenIcon = new L.Icon({
iconUrl: 'https://static1.squarespace.com/static/540ed918e4b0daae9995d1d7/54ecab60e4b0feaa477dac5a/54ecab79e4b0c686e92227d7/1424796549381/university.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
iconSize: [35, 40],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [10, 10]
});
var marker = L.marker([scoala[i]['latitudine'], scoala[i]['longitudine']], {
icon: greenIcon
}).addTo(groupA);
marker.bindPopup("<b>" + scoala[i]['scoala'] + "</b><br>Detalii:" + scoala[i]['detalii'] + "<br />Telefon: " + scoala[i]['telefon']);
L.Icon.Big = L.Icon.extend({
options: {
iconSize: new L.Point(44, 61),
iconUrl: 'https://static1.squarespace.com/static/540ed918e4b0daae9995d1d7/54ecab60e4b0feaa477dac5a/54ecab79e4b0c686e92227d7/1424796549381/university.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png'
}
});
var bigIcon = new L.Icon.Big();
marker.on('mouseover', function(e) {
this.openPopup();
marker.setIcon(bigIcon);
});
marker.on('mouseout', function(e) {
this.closePopup();
marker.setIcon(greenIcon);
});
}
}

Issue here is related to scope and async events.
marker.on('mouseover', function(e) {
this.openPopup();
marker.setIcon(bigIcon);//marker object is overwritten in the for loop each time
});
You can use instead
e.target.setIcon(bigIcon);
Same for mouseout
Otherwise you can do some wrapping with an immediatly invoked function to preserve scope, as so:
function(marker){
marker.on('mouseover', function(e) {
this.openPopup();
marker.setIcon(bigIcon);
});
}(marker)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With