Jcook894 Jcook894 - 1 month ago 19
Javascript Question

Marker animations

Im trying to implement a functionality that changes the marker color when you click them and when its closed or another marker is clicked it returns back to its default color. so far Ive gotten my code to change the color when its clicked but I cant seem to return the closed markers to the original color.

marker.addListener('click', function() {
this.setIcon(defaultMarker);
});

marker.addListener('click', function() {
this.setIcon(highlightedMarker);
});

google.maps.event.addListener(infoWindow,'closeclick', function(){
marker.setIcon(defaultMarker);
infoWindow.close(defaultMarker)

})


here is my js fiddle https://jsfiddle.net/Jcook894/88j5ud5h/

Answer

Your problem is that you set two click event on your marker and the last one, set the marker color to blue.

You can click many times you want, it will always be the blue at the end.

So, I :

  • removed the both marker click event : marker.addListener('click', function(){})
  • moved the .setIcon(highlightedMarker) in the Google Maps click listener
  • add a infowindow.closeclick event : when a infowindow is closed, the event is triggered.
  • add a custom attribute to your infowindowobject which is the marker object : infoWindow.marker = marker;
  • change the marker color by the default one in the infowindow.closeclick event : this.marker.setIcon(defaultMarker);

google.maps.event.addListener(marker,'click', ( function(marker, location){
  return function() {
     console.log("that " + location);
     streetViewService.getPanoramaByLocation(marker.position, streetRadius, getStreetData);
     infoWindow.marker = marker; // <-- HERE
     infoWindow.open( map, marker);
     infoWindow.setContent("<div>" + marker.title + "</div><div id='pano'></div><div><a href=" + location.url + ">"+ location.url +"</a></div>");
     this.setIcon(highlightedMarker); // <-- HERE
  }
})(marker, locationArray[i]));

google.maps.event.addListener(infoWindow,'closeclick',function(){
  this.marker.setIcon(defaultMarker); // <-- HERE
});

Here the JSFiddle