Creating a clickable Google map of blog posts using WP_Query in WordPress

Last year I completed a WordPress site that presents a collection of photographs taken for the Worktown Mass Observation project.

The site uses a custom post type for each photograph. One problem I had to get my head around was how to display all of these photographs on a clickable Google map.

Luckily I found this excellent tutorial by Marty Spellerberg which served as my jumping off point.

Ease of use

Marty’s method uses custom meta fields to pull in the data.  As there are about 800 photographs in the collection I wanted to make it easy for site editors to add the map data.

My workaround involved using Ben Huson’s WP Geo plugin which adds a handy drag and drop Google map to your post editor. Lattitude and longitude coordinates on the Worktown site are pulled from that.

On the front end it wasn’t going to be practical to display 800 or so map positions at once so I needed to adapt Marty’s solution to incorporate the Google MarkerClusterer library to tidy up the map and to make it load quicker for visitors.

The MarkerClusterer visually groups map pointers into a single clickable area. Clicking these automatically zooms the map into an area with a smaller cluster of pointers.

The code

If you check out Marty Spellerberg’s post first, then have a look at the Google MarkerClusterer documentation the following might make a bit of sense 🙂

The following would go in your map page template:

And in your .js file:

And the rest of this junk needs to go in your header (note you also need to have MarkerClusterer.js on your site too):