简体   繁体   中英

On click change icon then change back when clicking on other marker

I would like to add a onlick seticon function to change the icon when someone clicks on the marker and then change back when they click of that marker. I have tried

 google.maps.event.addListener(marker, 'click', function() {
marker.setIcon('/url.jpg')
 } 

But the icon changes back to the old icon after 1 second. Any help is appreciated.

This is the current code:

function readData() {
    var url = 'aircraft.json';
$.when($.getJSON(url)).done(function(data) {
    $.each(data.aircraft, function(i, value) {
        var plane = value;
      var myLatlng = new google.maps.LatLng(value.lat, value.lon, value.flight, value.altitude);
      if (markers[value.hex]) {
        markers[value.hex].setPosition(myLatlng);
        //console.log("moving marker for " + value.hex);
         markers[value.hex].setIcon(getIconForPlane(value)); 
       infoWindows[value.hex].setContent(text(value));




      } else {
        // create new
        markers[value.hex] =  new google.maps.Marker({
          position: myLatlng,
          icon: getIconForPlane(value),
          map: map,
          title: "Callsign: " + value.flight + ", Altitude: " + value.altitude,
        });
        //console.log("creating marker for " + value.hex);
        infoWindows[value.hex] = createInfoWindow(value, markers[value.hex] ,map)
      }

    });


  });

}

You could manage a window level var for keep trace of the previously selected marker and assign to this the normal icon on your listner

  var selectedMarker = null;

  .....


  google.maps.event.addListener(marker, 'click', function() {
    if (selectedMarker !== null){
      selectedMarker.setIcon('/normal_url_icon.jpg')
    }
    marker.setIcon('/url.jpg');
    selectedMarker = marker;
  } 

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