Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 719
wzazza Avatar asked Jun 11 '11 23:06

wzazza


2 Answers

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)

like image 174
bobfet1 Avatar answered Nov 18 '22 02:11

bobfet1


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.

like image 8
Trott Avatar answered Nov 18 '22 01:11

Trott