简体   繁体   中英

Leaflet Map - change only img marker when click on it

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);

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);


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM