Adding a custom Snazzy Map to WordPress

← back to the blog

Designers are incurable perfectionists. They always seem to want things that push just beyond what the current tools we as developers have available.

Until recently, outside widgets like Google Maps gave us a line in the sand. So that blue that Google uses for water doesn't quite match the blue in the logo? Too bad. Either use what we've got, or scrap that map and make a JPG.

Well, designers can celebrate (and developers curse) the arrival of Snazzy Maps. SnazzyMaps (an Edmonton company!) allows you to build your own styles using a WYSIWYG editor, then export the style information as JSON code. This can be interpreted by the Google Maps JavaScript API to apply the same styling to any map.

Here I will go over how to integrate a Google Map with custom styling into a WordPress site, but much of what I include will apply to any website. There are also a couple of premium plugins that work with SnazzyMaps, but I prefer the home-baked solution below.

Here are a couple different examples.

Le HTML

First off, we need to create a container for our Google Map. Generally, this is just a div with an explicit width and height (because it will be empty to start) and an ID (or class) to act as a JavaScript hook.

<div id="the-map"></div>

Note that you usually need to add an explicit height for this element in CSS, since it's empty when the page loads.

Le JavaScript

First we need to include both the Google Javascript file and a custom Javascript file to fire the API. The best way to do this in WordPress is to use wp_enqueue_script.

In functions.php:

<?php
    add_action('wp_enqueue_scripts', 'my_enqueue_scripts');
    function my_enqueue_scripts() {
        wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false', array(), null, true);
        wp_enqueue_script('script', get_stylesheet_directory_uri() . '/js/script.js', array('google-maps'), null, true);
    }
?>

The second enqueued script will be our main javascript file used for setting up Google maps. Calling the Google Maps API is extremely simple, depending on the level of customization. The biggest thing to decide at this stage is where the map will be centered and how "zoomed-in" it will be. The full documentation for including a Google map can be found at developers.google.com.

In script.js:

function makeMap() {
  var map = new google.maps.Map(document.getElementById('the-map'), {
      center : new google.maps.LatLng(49.278094, -122.919883),
      zoom : 13,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true
  });
  var marker = new google.maps.Marker({
      position : new google.maps.LatLng(49.278094, -122.919883)
  });
  marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', makeMap);

Adding SnazzyMaps Styling

Custom styles can be passed directly into the Google maps object. Snazzy maps outputs these styles as JSON code which can be parsed in JavaScript and passed in. But where should the JSON code go? Javascript generally doesn't like multi-line strings, and the compressed JSON is going to be ugly. Adding it directly to a JS file combines style and functionality, something that developers should try to avoid.

There are probably several good ways of accomplishing this, but I want to share one method that achieves very clean seperation of information. It uses the little known WordPress function wp_localize_script. This is an extremely useful function which allows us to pass data from PHP to JavaScript without awkwardly storing it in HTML (for example, in a hidden element).

Lets copy and paste the JSON from SnazzyMaps into a file called map_style.json and save it in the same directory as functions.php. Then, lets add to our my_enqueue_scripts function:

<?php
    add_action('wp_enqueue_scripts', 'my_enqueue_scripts');
    function my_enqueue_scripts() {
        wp_enqueue_script('google-maps', 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false', array(), null, true);
        wp_enqueue_script('script', get_stylesheet_directory_uri() . '/js/script.js', array('google-maps'), null, true);
        wp_localize_script( 'script', 'wpGlobals', array(
            'mapOptions' => file_get_contents( dirname(__FILE__) . '/map_style.json' )
          ) );
    }
?>

Load the relevant page, then open up a console and type wpGlobals. The console should return { mapOptions : and then a long string representing the map styles we created. Finally, let's modify the Javascript code from above:

In script.js:

function makeMap() {
  var snazzyMap = JSON.parse(wpGlobals.mapOptions);
  var map = new google.maps.Map(document.getElementById('the-map'), {
      center : new google.maps.LatLng(49.278094, -122.919883),
      zoom : 13,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true,
      styles : snazzyMap
  });
  var marker = new google.maps.Marker({
      position : new google.maps.LatLng(49.278094, -122.919883)
  });
  marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', makeMap);

UPDATE FEB 26th: Big thanks to David Rizzuto (@davidrizutto) for his comments below. I've fixed a couple of mistakes and clarified some other things.

UPDATE SEPT 8th: Additional thanks to @teejK who noticed I was using the experimental version of Google Maps.