oym
oym

Reputation: 7083

Javascript callback and google maps api question

I am using google maps api v3 and have an array of arrays object:

MVCArray.<MVCArray.<LatLng>>

I want to iterate over this. I see that MVCArray has a method forEach which uses a call back, but I have no idea how to use this (I haven't done much js). The api defines this method as follows:

forEach(callback:function(*, number)))

Could somebody please show me an example of how to use this given an MVCArray of MVCArrays (I need to pull out each LatLng object)?

Upvotes: 1

Views: 2366

Answers (2)

khany
khany

Reputation: 1187

just to clarify @VoteyDisciple's answer, here is a real life example

aMarker is the MVCArray object which, by default, has draggable set to false. so when the user switches to 'true', my code calls this:

aMarker.forEach(function(item, index) {
    aMarker[index].setDraggable(true);
});

and makes them draggable.

Upvotes: 1

VoteyDisciple
VoteyDisciple

Reputation: 37823

In JavaScript, you can pass around functions in the same way you can pass around any other sort of data. There are two usual ways of approaching this.

First, you could define a function in the usual way and give it a name:

function myHappyFunction(item, index) {
   // Do things using the passed item and index
}
...forEach(myHappyFunction);

Here you're passing the function you've created into the forEach function. myHappyFunction will now get called a bunch of times, each time passing a different item from the list.

Alternatively, you can avoid the need to come up with a clever function name by just passing a function DIRECTLY, like so:

...forEach(function(item, index) {
    // Do things using the passed item and index
});

This behaves the same way, but without the need to develop a unique name for each and every function you might want to pass around.

Upvotes: 2

Related Questions