I want to display an alert with the marker info when I click on it. I receive the parameters as a json and my problem is when I click any marker, it is always displaying the info of the last marker. I don´t know where the problem can be.
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var userPos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude)
var markUsr = new google.maps.Marker({
position: userPos,
map: map,
icon: 'images/locblue.png'
});
map.setCenter(markUsr.position);
for (var i = 0; i < data.length; i++) {
var pos = new google.maps.LatLng(data[i].latitud, data[i].longitud)
var marker = new google.maps.Marker({
position: pos,
map: map,
icon: 'images/locred.png',
description: data[i].desc
});
var infowindow = new google.maps.InfoWindow({
content: data[i].name
});
infowindow.open(map, marker)
google.maps.event.addListener(marker, 'click', function () {
alert(marker.description)
})
}
})
}
I had almost the exact same problem with Google Maps. As far as I understand (which would explain the problem and solution), when you click a marker, JS essentially goes back to the scope of wherever google.maps.event.addListener
is called. However, it doesn't store n
(data.length
) different marker
variables. It just remembers the last one.
To solve this, create a list of markers before the for loop, and reference indices in the list instead of just one marker
variable. Store the index of each marker in an id
property to keep it available. Like this:
...
map.setCenter(markUsr.position);
var markers = [];
for (var i = 0; i < data.length; i++) {
var pos = new google.maps.LatLng(data[i].latitud, data[i].longitud);
markers[i] = new google.maps.Marker({
position: pos,
map: map,
icon: 'images/locred.png',
description: data[i].desc,
id: i
});
var infowindow = new google.maps.InfoWindow({
content: data[i].name
});
infowindow.open(map, markers[i]);
google.maps.event.addListener(markers[i], 'click', function () {
alert(markers[this.id].description)
})
}
...
Sometimes JS can be very unintuitive, but this is how I solved it.
As a side note, you were missing a couple of semicolons.