Maverick283
Maverick283

Reputation: 1403

Google Maps API add Listeners to an array of markers

I have a map displaying markers based on a database that are saved in an array. Now I want to add an animation to them. Quick research gave me information about single markers yet no hint how I could perform those actions to multiple markers.

Being pretty much new to Javascript, I am not quite sure how to perform this.

I have a php based foreach loop, in which the markers are added. (Database requests will only work with php as far as I understand).

I tried inserting

google.maps.event.addListener(flightMarkers[flightMarkers.length], 'click', flightMarkers[flightMarkers.length].setAnimation(google.maps.Animation.BOUNCE););

but then the map is not even displayed anymore.

Any Ideas and hints are greatly appreciated! Thanks in advance.

Upvotes: 1

Views: 1427

Answers (2)

Maverick283
Maverick283

Reputation: 1403

Thanks to @Dr.Molle and @Lukas Kovac this is what works:

 for (var i = 0; i < flightMarkers.length; i++) {
              google.maps.event.addListener(flightMarkers[i], 'click',

              function () {
                  this.setAnimation(google.maps.Animation.BOUNCE);
              });
          }

Upvotes: 0

Lukas
Lukas

Reputation: 817

flightMarkers.length contains number of items in flightMarkers.

So when you have

flightMarkers = new Array();
flightMarkers[ 0 ] = "value";
flightMarkers[ 1 ] = "value";
flightMarkers[ 2 ] = "value";

flightMarkers.length will contain number 3, but the last index in that array is 2. And when you type flightMarkers[flightMarkers.length] in this example it will be flightMarkers[3], which is undefined.

If you want to add listener only to last marker, use flightMarkers[flightMarkers.length - 1]. If you want to add listener to every marker, use for loop:

for( var i = 0; i < flightMarkers.length; i++ ) {
    google.maps.event.addListener(flightMarkers[i], 'click', 
    flightMarkers[i].setAnimation(google.maps.Animation.BOUNCE););
}

Upvotes: 2

Related Questions