Custom Google Maps

Get a customised Google map on your page.

The Google maps Javascript API v3 offers lots of opportunities to customise Google maps. This gives you the best of both worlds – the map can be styled to match the client website’s branding, whilst retaining all the functionality of Google maps.

To display your map, you need to:

  1. Define (style) a div to be used as a map canvas
  2. Initialise Google Maps
  3. Define the map – when working in WordPress I prefer to save this as a *.js file and enqueue this

It’s important that these three elements are added to the document head, in the specified order. You can see this in action in the “Enqueue Scripts” gist at the end of this post.

The Google Styled Maps Wizard is a useful way of coding custom JSON data to be passed to your map, which is how it the map gets it’s custom style. It’s not a particularly great way of creating an entire map, but it’s useful for getting the right JSON data for particular element.

Here’s an example of a customised Google map that was created with a client’s brand colours:

Coding the Map

Here’s the code used for this map:

Enqueue Scripts

You need to queue up the relevant Javascript and style rules on the page that will display your map. This needs to be done in the right order.

The functions and action hooks below enqueue map styles and scripts properly. They could be added to the active theme functions.php file, or they could be adapted for use in a plugin.

The code uses the really useful wp_localize_script function (see line 36 above) which is used to pass variables defined in PHP into a Javascript function.

In this case, we’re defining the path to a marker image from within custom.php. This avoides hardcoding the path to the image in Javascript, which is best practice and helps ensure the site can be deployed to it’s final location easily and without incident.