I have several markers on my google map. Each has text that should show when it is clicked in the form of an infowindow. The code for all this is below. Hwever, the problem is that, when I click any marker on the map, its always the same marker that the map zooms in on and the same marker’s infoWindow pops up. No matter where I click its always the same.
Wondering if there is something in plain sight that Im doing wrong. Could someone give me some advice?
function getlistings()
{
$.getJSON('list/listings.json', processlistings);
}
function processlistings(data)
{
listings = data;
markersArray = [];
for( i = 0; i < listings.length; i++)
{
var listing = listings[i];
var markerLatLng = new google.maps.LatLng(parseFloat(listing["latitude"]), parseFloat(listing["longitude"]));
marker = new google.maps.Marker({
position : markerLatLng,
title: listing['name'],
map : map
});
var infowindow = new google.maps.InfoWindow(
{
content: listing['name'],
position: markerLatLng
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map);
});
markersArray.push(marker);
}
}
When you loop through your data, you are creating an
InfoWindowmany times over. At the end of the loop, you have oneInfoWindowatmarkerLatLng.When the marker is clicked,
infowindow.open()is called, which uses the infowindow atmarkerLatLng.You need to use a function closure, as demonstrated at http://www.geocodezip.com/v3_MW_example_map1.html