Google Maps API v3, how to change the marker icon when clicked

How can I change the marker icon when a marker is clicked (during a click event) and return it to the normal value icon when another marker is clicked?

+7
source share
2 answers

I have not tested this code, so there may be typos or errors, but it should give you this idea.

First, define a callback to set all the markers to a regular icon (before resetting any previously clicked markers) and set the current marker icon of the marker pressed to the selected icon:

var markerCallback = function() { for (var i=0; i<arrayOfMarkers.length; i++) { arrayOfMarkers[i].setIcon(normalIcon); } this.setIcon(selectedIcon); } 

Then assign a callback to the click event on each token like this:

 google.maps.event.addListener(marker, 'click', markerCallback); 

Of course, some code improvements can be made. For example, you may not want normalIcon , selectedIcon and arrayOfMarkers be global variables, as the code above suggests. And if you have a lot of markers, you probably want to track the previously selected marker instead, rather than have a for loop reset icon on each of them.

But, as I said, this should give you this idea.

+6
source

In any case, someone wants to see an example of tracking the previous marker in a global variable, as Casper mentioned, here is what I did:

 google.maps.event.addListener(marker,'click',function() { if (selectedMarker) { selectedMarker.setIcon(normalIcon); } marker.setIcon(selectedIcon); selectedMarker = marker; }); 

(after setting selectedMarker as a global variable)

+14
source

All Articles