This is part of a series of posts that I wanted to do around late October last year, I finally got to it.
When I was doing an assignment in Internet Programming last semester, we were given the task of using the Google Maps API. This assignment also required the use of custom markers, and to have Info Windows that are displayed upon clicking the multiple custom markers.
The Google Maps API example for InfoWindows was useful in displaying only one info window (a window with additional information if a marker is clicked), and this led me to thinking I could instantiate a new InfoWindow and add an event listener to it.
Something like this:
However, this led to the InfoWindow only displaying information about the last item in the array of objects, no matter which marker I clicked.
After a bit of head scratching and Google-fu, I then realized I had stumbled onto an issue caused by closures.
The actual problem
Infowindow to be opened is the last item in the data array we iterated through. Coming from a mostly-Java background, this confused me for a little bit as the same kind of code in Java would not have this ‘weird’ issue of all custom markers (in an array) only displaying information from the last item in the data array.
- Adding the Infowindow object to the marker itself, using a key
We can explicitly create a reference to a specific infowindow by assigning it to a custom key to the marker object, and then later retrieving it by using that reference when the marker is clicked and the event is fired. By assigning the infowindow to a marker property, each marker can have it’s own infowindow.
This was how I approached the problem, with the relevant sample code.
- Using anonymous function wrapping
Couldn’t have done it without those answers that were contributed by other developers. I highly recommend you read that answer for even more info.
Code for my assignment can be found here, as part of the