Attempting to generate infowindows for markers within a Google Map, I utilized an array to create "disposable objects" within a for loop. Unfortunately, my approach is not yielding the desired results. Clicking on the markers has no effect, and upon checking the console, I encounter the following error message:
Uncaught TypeError: Cannot call method 'open' of undefined
Not assigning the object to an array index causes each marker click to only open the last info window (as the object being overwritten updates all references to previous objects).
How can I resolve this issue?
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 issue lies in the 3rd to last line of the code above (
infowindows[counter].open(map, markers[counter])
)
Answer
While every response to this question contributed to finding a solution, I ultimately resolved it using a forEach loop:
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])