wzazza
wzazza

Reputation: 73

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

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?

Upvotes: 7

Views: 12491

Answers (2)

bobfet1
bobfet1

Reputation: 1633

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)

Upvotes: 17

Trott
Trott

Reputation: 70055

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.

Upvotes: 8

Related Questions