defsounds

http://revisedagain.com/wp-content/themes/r

Animate One Marker At A Time In Google Maps Api 3

Posted on July 5th, 2011 Animate One Marker At A Time In Google Maps Api 3

I’ve been working on a mashup app using Google Maps API 3 lately and without barely any knowledge of Jquery/JS, it hasn’t been the easiest thing.

Believe it or not, one of the biggest challenges was trying to only animate on marker at a time. So the desired effect would be–when a user clicks one marker, the last marker clicked becomes inanimate

To achieve this, we have to do the following:

  1. Create our markers in an array.
  2. Add click event.
  3. Add unique identifier.
  4. Iterate through array, kill all previous animations, and fire up the animation for current marker. (It’s actually easier than it sounds).

So let’s get started..I’ll be using a JSON return to create the markers..Also remember to declare your marker array variable with a global scope.

  
  1. var marker = [];

Then use getJSON to pull the info.

  
  1. $.getJSON("URL OF JSON", {}, function(data){
  2.    });

Now we’ll do a for each item statement to fill the array

  
  1. $.each(data.jsonitem, function(i, item){
  2.  
  3. marker[i] = new google.maps.Marker({
  4.     map:map,
  5.     id: item.id,
  6.     title:item.name,
  7.     animation: google.maps.Animation.DROP,
  8.     icon: "images/pin_"+item.type+".png",
  9.     position: new google.maps.LatLng(item.lat, item.lng)
  10.   });

My unique identifier is id:item.id ..which is the number of the row from my Database.  The title, position, and Icons are also pulled from the JSON return. 

Now that we have an array of our markers we’ll  write up a quick action that says..in plain english.. Remove the animation from all other markers and if the id of this marker matches one in the array..animate it. You’ll add this to the click function  of your marker:

  
  1. //marker click functions
  2. google.maps.event.addListener(marker[i], 'click', function() {
  3. for( var i in marker ){
  4.      marker[i].setAnimation(null);
  5.      if( marker[i].id == item.id ) marker[i].setAnimation(google.maps.Animation.BOUNCE);
  6. }

 

Leave a comment