In an effort to create infowindows for markers inside of a Google Map, I have used an array to create "disposable objects" inside of my for loop. However, my method does not seem to be working. Clicking on the markers does nothing, and when I check the console, I am getting this error message:
Uncaught TypeError: Cannot call method 'open' of undefined
When I don't assign the object to an array index, clicking on any of the created markers only opens the last info window (meaning that when the object is overwritten, it updates all of the references to the previous objects).
How can I circumvent this?
markers = []
infowindows = []
counter = 0
for location in exports.response.locations
myLatlng = new google.maps.LatLng(location.latitude, location.longitude);
markers[counter] = new google.maps.Marker(
position: myLatlng
map: map
title: location.name
)
contentString = '<div id="info_content_' + location.id + '">' + '<h3>' + location.name + '</h3>' + '<ul>' + '<li>' + location.address + ', ' + location.city + '</li>' + '</ul>'
infowindows[counter] = new google.maps.InfoWindow(content: contentString)
google.maps.event.addListener markers[counter], "click", ->
infowindows[counter].open(map, markers[counter])
counter++
note
the problem area is the 3rd to last line in the code above. (infowindows[counter].open(map, markers[counter])
)
answer
Virtually every reply to this question helped me find a fix, but - for the record (and anyone readying this later) I solved it with a foreach:
markers = []
infowindows = []
exports.response.locations.forEach (location) ->
myLatlng = new google.maps.LatLng(location.latitude, location.longitude);
markers[location.id] = new google.maps.Marker(
position: myLatlng
map: map
title: location.name
)
contentString = '<div id="info_content_' + location.id + '">' + '<h3>' + location.name + '</h3>' + '<ul>' + '<li>' + location.address + ', ' + location.city + '</li>' + '</ul>'
infowindows[location.id] = new google.maps.InfoWindow(content: contentString)
google.maps.event.addListener markers[location.id], "click", ->
infowindows[location.id].open(map, markers[location.id])