How can I change a marker icon when a marker is clicked (on a click event) and return it back to a normal icon when another marker is clicked?
Just in any case anyone wants to see an example of keeping track of the previous marker in a global variable like Kasper 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)
I haven't tested this code, so there may be a typos or bugs, but it should give you the idea.
First, define a callback to set all markers to the normal icon (to reset any previously clicked markers) and set the current clicked marker's icon to the selected icon:
var markerCallback = function() {
for (var i=0; i<arrayOfMarkers.length; i++) {
arrayOfMarkers[i].setIcon(normalIcon);
}
this.setIcon(selectedIcon);
}
Then, assign the callback to the click event on each marker like so:
google.maps.event.addListener(marker, 'click', markerCallback);
There are certainly some code improvements that could be made. For example, you might not want normalIcon, selectedIcon, and arrayOfMarkers to be global variables the way the code above assumes they are. And if you have a lot of markers, you probably want to instead keep track of the previously selected marker rather than having a for loop reset the icon on every one of them.
But like I said, this should give you the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With