I have the same event listener for many markers in my javascript. How do I differentiate between different markers in this listener? I want to display another marker elsewhere on clicking of a particular marker. Every marker has another marker which I display on clicking on it.
the event listener code
google.maps.event.addListener(marker, 'click', function() {
//code goes here
});
more detail:
I have 2 arrays markers1 and markers2 each having 10 markers. I display the 10 from markers1 on my map. On clicking markers1[0] marker I want to display the markers2[0] marker on the map. How do I know in the event listener that I have clicked on markers1[0], now I know that I can use the THIS for identifying markers1[0] but how do I know in the listener that it was the marker at the position 0 in array markers1 so that I could also display marker at position 0 in array markers2?
What you can do is have an external function which handles the adding of markers/infowindows (see 150PoundsOfDonamite's comment). Coincidentally I wrote a blog post today that shows how to do this.
You can easily add the index (or any other information) to each Marker:
Then in your event handler you can do this:
The setVisibility function would be similar to the one suggested by 150PoundsOfDonamite above, except that you know the index of the marker that you want to make visible:
Do you mean that the
marker
variable is an array of markers? Or do you mean that the code you have is duplicated for each marker? Because if the latter is the case, then in each call to addListener,this
refers to the marker in question.Update after comments
Ok, then you can use a function that just loops through your
marker1
:Then each individual click listener definition will look like this:
However, you don't want to do something like that 10 times, so you need to put it in a pattern like this:
Where
marker1Data
is just an array of LatLng objects that define the location of each marker inmarker1
. And of course a for loop formarker2
, but withvisible: false
.You don't actually have the same listener for each marker, or at least not the same handler function; you just have the same code.
In JavaScript, functions are first-class objects, and in all the answers posted so far, a separate function is being created for each marker. This is a waste of memory.
Here's what I think you want:
something like this? hope this helps