API v2.75 (2.x) now introduces the
setImage method for
GMarker, as noted in the forums. In the past, changing the image of a marker usually required creating multiple arrays of markers for each image change and some tricky switching between the arrays. Now changing the image just requires one method call.
To show one way you could exploit
GMarker.setImage for all its worth, I've created a simple marker-clicking game, based on the Whack-a-Mole game found in arcades. Try it out, and find out how its done below.
Here's how it works:
load, I set up the map and call
createMarker for each of the points in the
moleLocations array, adding each of the returned markers to a global
createMarker, I create a marker with the global
GIcon iconMole which has the default
'mole_down.png' image for its
Note: I created all the mole images with the same canvas size (36*42px), as calling
GMarker will not resize the
GIcon. The new image will just be resized to fit the original
createMarker, I extend
Marker with a
whackState property so I can keep track of the state of a mole hole.
I also add
mouseout listeners to the marker. In the
click listener, I check if the game is being played and if the current marker is in the up
whackState. If so, I increment the global
marker.setImage('mole_down.png'), and change the
almostDown. In the
mouseout listeners, I toggle between
'mole_up.png' if the mole is currently in the up
Fast clickers will barely notice the
mouseover state, but it's always nice to have a
mouseover state to provide additional feedback to the player.
When the player clicks the start button, I iterate through the
markers array, calling
marker.setImage('mole_down.png') and setting
'down'. I also reset the game seconds left and current score, and call
setInterval(popMoles, 1000) so that the
popMoles function will get called every second.
popMoles, I iterate through the
markers array and pick a random number between 1 and 3 for each. If the marker is in the down
whackState and the random number picked is 1, I pop the mole up by calling
marker.setImage('mole_up.png') and setting its
whackState to up. If the marker is in the almostDown
whackState, I set its
whackState to down. This intermediary state ensures that markers won't pop up immediately after getting whacked down. I then increment the game seconds and update the score. If the game seconds played equals the game duration (30), I call
endGame, I iterate through the
markers array, calling
marker.setImage('mole_happy.png') for every marker currently in the up
whackState. I also clear the timer that was calling
popMoles every second.
Here's a direct link to the page, if you want to check out the source code yourself.