Reputation: 61
I'm using my database to get different positions that will be set on a Google Map as markers. I'm using JavaScript to also set event listeners for all these dynamically loaded markers, but I have a problem with this one:
var markerCollection = [];
//pushing data into the array...
for ( var j = 0; j < markerCollection.length; j++) {
console.log(j + ' ' + markerCollection[j].shopId);
$.proxy(google.maps.event.addListener(markerCollection[j].gmapMarker, "click", function(e) {
console.log(markerCollection[j].shopId);
}),this);
}
The code tells me markerCollection[j]
is undefined. Yet if I type a hardcoded way (markerCollection[0]) it will work. Why does this happen and how do I fix it?
Upvotes: 0
Views: 69
Reputation: 28880
The code in the answer linked in one of comments is more complicated than it needs to be. There is a simpler way to do this that is easier to understand:
var markerCollection = [];
//pushing data into the array...
for ( var j = 0; j < markerCollection.length; j++) {
addMarker( markerCollection[j] );
}
function addMarker( marker ) {
console.log( marker.shopId );
google.maps.event.addListener( marker.gmapMarker, "click", function(e) {
console.log( marker.shopId );
});
}
That's really all you need. Each time the addMarker()
function is called, that invocation of the function has its own marker
variable which refers to one of the elements in the markerCollection
array. And that marker
variable remains valid when the listener callback gets called later in response to a click.
It's doing the same thing as the more complicated version, but in a way that I think is much easier to follow. Note how the code in addMarker
uses the marker
variable instead of having to say markerCollection[i]
every time.
Also, you don't need the $.proxy()
bit unless you need to pass a this
value along, which you're not using here. So leave it out if you don't need it. Simpler is better!
Upvotes: 3