I am trying to create interactive markers in Google maps. Here is the array to create the markers:
var markers = [
{"id":17,"ti":"33 Star Hotel","lat":3.14648,"lng":101.711,"ty":5,"lid":"3","desc":""},
{"id":9,"ti":"Aquaria KLCC","lat":3.15392,"lng":101.713,"ty":10,"lid":"3","desc":""},
{"id":28,"ti":"Batu Ferringhi","lat":5.47436,"lng":100.247,"ty":15,"lid":"4","desc":""},
];
The markers are added to the map n if the markers location id lid is equal to n.
When a marker is clicked, I want the markers array index to be displayed, but they all show the final value of i (markers.length).
function map_center(n) {
for ( var i = 0; i < markers.length; i++ ) {
if ( markers[i].lid == n ) {
var m = new google.maps.Marker({
position: { lat: markers[i].lat, lng: markers[i].lng },
map: map,
title: markers[i].ti,
icon: icons[markers[i].ty],
});
m.addListener( "click", function(){
alert("click:" + i );
});
markers[i].dom = m;
}
}
}
Somehow, the anonymous function needs a parameter to get a copy of the current value of i. I found this solution here on SO and it works, but i do not like passing parameters this way:
var m = new google.maps.Marker({
position: { lat: markers[i].lat, lng: markers[i].lng },
map: map,
title: markers[i].ti,
icon: icons[markers[i].ty],
i: i
});
m.addListener( "click", function(){
alert("click:" + this.i );
});
How should this be done properly?