Home > Net >  Leaflet Map - change only img marker when click on it
Leaflet Map - change only img marker when click on it

Time:06-02

Im triying to change image marker when user click on a specific one. the problem here, is when i click on a market img changes, but when i click out side or onother market, nothing happens. (Screen shor below)

Please check here

This if my JS :

var LeafIcon = L.Icon.extend({
  options: {
    iconSize: [38, 95],
    iconAnchor: [22, 94],
    shadowAnchor: [4, 62],
    popupAnchor: [-3, -76],
  },
});

var greenIcon = new LeafIcon({
    iconUrl: project.path.base   "images/map/marker-in.png",
  }),
  redIcon = new LeafIcon({
    iconUrl: project.path.base   "images/map/marker-active.png",
  });


var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
  .on("click", (e, j) => {
    e.target.setIcon(redIcon);
    console.log("target", e.target)
  })
  .addTo(map)
  .bindPopup($popin.innerHTML);

CodePudding user response:

Remeber the last selection and reset that marker


var greenIcon = new LeafIcon({
    iconUrl: project.path.base   "images/map/marker-in.png",
  }),
  redIcon = new LeafIcon({
    iconUrl: project.path.base   "images/map/marker-active.png",
  });

var lastMarker;
var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
  .on("click", (e, j) => {
    if(lastMarker){
       lastMarker.setIcon(greenIcon);
    }
    e.target.setIcon(redIcon);
    console.log("target", e.target)
    lastMarker = e.target;
  })
  .addTo(map)
  .bindPopup($popin.innerHTML);

A different way is to set and reset the marker always when the popup is opend / closed:

var testmarker = L.marker([data.lat, data.lng], { icon: greenIcon })
  .on("popupopen", (e) => {
    e.target.setIcon(redIcon);
  })
.on("popupclose", (e) => {
    e.target.setIcon(greenIcon);
  })
  .addTo(map)
  .bindPopup($popin.innerHTML);


  • Related