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.

Google Maps InfoWindow


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

Assuming that you have the content already able to be retrieved from a JavaScript object or a JavaScript array, you can build up the HTML string and store it in a variable called, say, sContent.

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 info property:

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 infoWindow itself.

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.