Recently, I’ve been working with the Google Maps API in order to plot locations that are stored as custom post type meta data in the WordPress database.
The general functionality is as follows:
- For each of the locations stored in the database
- Generate a pin for the location
- In addition to creating a pin, create an information window that shows the pin’s location
The information windows that sit above the flags are also called
infowindow within the context of the API.
The Google Maps API documentation is pretty good in covering stuff like this, but I did run into a couple of gotchas when working with it, so I thought I’d document them here just in case anyone runs into the same problem.
Multiple InfoWindows with Google Maps
It may look something like this:
Next, you’ll want to actually create the
infoWindow object with this information. This is easy to do and follows exactly what the documentation specifies:
Next, I like to add the information as a proper to the
marker object so that I can access it more easily when I’m with with said marker. To do that, I simply added it as an
This is where it gets a little confusing. Rather than following the API’s suggestion of doing this:
We have to actually set the content of the current instance of the
infoWindow but when we do this, the scope of our variables change such that
this references to the current
marker. This is important to understand as you’re going to be passing the
info property to the
infoWindow (I told you it was going to get confusing :), and you’re passing an instance of the
marker to the
See the following code:
Like I said, it’s confusing.
You’re not likely to see this crop up unless you’re working with multiple pins with the Google Maps API, but I wanted to document it here just in case someone else were to run into the same problem.