Dev Notes

Software Development Resources by David Egan.

Custom Google Maps in Roots


Google Maps, Roots, WordPress
David Egan

Introduction

The Google maps JavaScript API v3 offers lots of opportunities to customise Google maps. The map can be styled to match the client website’s branding, retaining all the functionality of Google maps.

To display a custom Google map:

  • Define (style) a div to be used as a map canvas
  • Initialise Google Maps
  • Define the map – when working in WordPress consider saving the map as a *.js file and enqueueing this

It’s important that these three elements are added to the document head in the specified order.

The Google Styled Maps Wizard is a useful way of coding custom JSON data to be passed to your map, which is how 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.

Map Script & File Locations

Save the custom map script:

theme/assets/js/vendor

Placing the map in this location means that it won’t be uglified by Grunt. This keeps the file out of the concatenation group, and allows us to control exactly when and where it is enqueued.

The Grunt task in Roots concatenates all js files into a single file: /assets/js/scripts.min.js. For the most part this works well, as it reduces HTTP requests and thereby gives a performance boost.

Sometimes we want to keep scripts out of the main js file - in this case, we only want to call the Google maps API and run our custom script on a single page. Therefore, the map script should be placed in the /assets/js/vendor directory.


Enqueuing Scripts in Roots

Within the Roots structure, enqueuing of scripts is controlled in the theme/lib/scripts.php file.

Scripts can be enqueued conditionally (for example only on certain pages, as in the example below). The order in which scripts are deployed can also be controlled.

In this file, define the map canvas:

function carawebs_map_style() {

	// Run on page 69 only
	if (is_page('69')) {
		echo '<style>#map_canvas { width: 100%; height: 548px; }</style>';
	}
}

Initialise the Google maps API on a specific page:

function carawebs_initialise_googlemaps(){

	if (is_page('69')) {
	    $googlescript = '<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>';
	    echo $googlescript;
	}
}

Set up the map control script:

function carawebs_googlemaps_control(){

	if (is_page('69')) {

    // Register the control script - note script location
    wp_register_script( 'carawebs_googlemap', get_template_directory_uri() . '/assets/js/vendor/google-map.js');

		// Pass variables to the script - this avoids having to hardcode the map marker in javascript
		// This could be a user-selected field
		$imagelocation = get_template_directory_uri() . . '/assets/img/marker.png';
		$site_variables = array(
			'markerImage' => $imagelocation
			);

		wp_localize_script( 'carawebs_googlemap', 'carawebsMapVars', $site_variables );
		// This function makes variables available to carawebs_googlemap
		// Define the image in js like this: var image = (carawebsMapVars.markerImage);

	// Enqueue the map controls
    wp_enqueue_script('carawebs_googlemap');

	}
}

Insert scripts & style definitions in the correct order in wp_head:

// Add hooks for front-end
add_action('wp_head', 'carawebs_map_style', 1);
add_action('wp_head', 'carawebs_initialise_googlemaps', 2);
add_action('wp_enqueue_scripts', 'carawebs_googlemaps_control', 105);

The Entire Enqueue Script

/*================================================
* The Google Map Script
* ==============================================*/

/* Add Google Map Script to Specific Page */

function carawebs_map_style() {

	// Run on page 69 only
	if (is_page('69')) {
		echo '<style>#map_canvas { width: 100%; height: 548px; }</style>';
	}
}

function carawebs_initialise_googlemaps(){

	if (is_page('69')) {
	    $googlescript = '<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>';
	    echo $googlescript;
	}
}

function carawebs_googlemaps_control(){

	if (is_page('69')) {

    // Register the control script
    wp_register_script( 'carawebs_googlemap', get_template_directory_uri() . '/assets/js/vendor/google-map.js');

		// Pass variables to the script - this avoids having to hardcode the map marker in javascript
		// This could be a user-selected field
		$imagelocation = get_template_directory_uri() . . '/assets/img/marker.png';
		$site_variables = array(
	    'markerImage' => $imagelocation
	    );

		wp_localize_script( 'carawebs_googlemap', 'carawebsMapVars', $site_variables );
		// This function makes variables available to carawebs_googlemap
		// Define the image in js like this: var image = (carawebsMapVars.markerImage);

		// Enqueue the map controls
    wp_enqueue_script('carawebs_googlemap');

	}
}


// Add hooks for front-end
add_action('wp_head', 'carawebs_map_style', 1);
add_action('wp_head', 'carawebs_initialise_googlemaps', 2);
add_action('wp_enqueue_scripts', 'carawebs_googlemaps_control', 105);

/*====================================================================*/

The Google Map Script

The following is a sample custom Google map, saved as /assets/js/vendor/google-map.js

var carawebsMap;
		function initialize() {
		var myOptions = {
			zoom: 9,
			center: new google.maps.LatLng(52.693032,-8.864808),
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			scrollwheel: false,
			disableDefaultUI: false,
			styles:
        [
          {"featureType":"water",
					"stylers":[{"visibility":"on"},{"color":"#3bade2"}]},
          {"featureType":"landscape","stylers":[{"color":"#f2e5d4"}]},
          {"featureType":"road.highway","elementType":"geometry",
						"stylers":[{"color":"#777777"}]},
          {"featureType":"road.arterial","elementType":"geometry",
						"stylers":[{"color":"#c0c0c0"}]},//#e4d7c6
          {"featureType":"road.local","elementType":"geometry",
						"stylers":[{"color":"#fbfaf7"}]},
          {"featureType": "road.highway", "elementType": "labels",
						"stylers": [{ "visibility": "off" }]},
          {"featureType": "transit.line", "elementType": "labels.icon",
						"stylers": [{ "visibility": "off" }]},
          {"featureType":"poi.park","elementType":"geometry",
						"stylers":[{"color":"#c5dac6"}]},
          {"featureType":"administrative",
						"stylers":[{"visibility":"on"},{"lightness":33}]},{"featureType":"road"},
          {"featureType":"poi.park","elementType":"labels",
						"stylers":[{"visibility":"on"},{"lightness":20}]},{},
          {"featureType":"road","stylers":[{"lightness":20}]}]
        };

		carawebsMap = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		// Define an image to be used as a marker
		// var image set from wp_localize_script in the enqeueing function
		var image = (carawebsMapVars.markerImage);


		var centreLatLng = new google.maps.LatLng(52.693032,-8.864808);
        /* School Co-ordinates */
        var ennisLatLng = new google.maps.LatLng(52.847079,-8.987698); // Ennis Community College
        var ennistymon1LatLng = new google.maps.LatLng(52.941578,-9.289763); // Ennistymon CBS

    /*===============================
      Position the Markers
    ===============================*/
    var marker = new google.maps.Marker({
			position: ennisLatLng,
			icon: image,
			map: carawebsMap,
			title: 'Ennis Community College'
        });

    var marker2 = new google.maps.Marker({
			position: ennistymon1LatLng,
			icon: image,
			map: carawebsMap,
			title: 'Ennistymon CBS'
        });

      /*===============================
        Content Strings for Markers
      ===============================*/

      // Ennis Community College
        var ennisContentString =
        '<div id="content" style="color: #666;">'+
        '<h4 id="firstHeading" class="firstHeading">Ennis Community College</h4>'+
        '<div>'+
        '<p><b>Ennis Community College</b> is where we started<br>'+
        'our first School Cafe. We have been providing a service<br>' +
        'for the staff and students since 2009 -<br>'+
        'when we converted an old cupboard into a<br>'+
        'fully functioning school canteen.</p>'+
        '</div>'+
        '</div>';

      // Ennistymon CBS
			 	var ennistymon1ContentString = '<div id="content" style="color: #000;">'+
				 '<h4 id="firstHeading" class="firstHeading">Ennistymon CBS</h4>'+
				 '<div id="bodyContent">'+
				 '<p>Some information about Ennistymon CBS.</p>'+
				 '</div>'+
				 '</div>';

    /*===========================
      Set the InfoWindow
    ===========================*/

			var ennisInfowindow = new google.maps.InfoWindow({
                content: ennisContentString
            });

			var ennistymon1InfoWindow = new google.maps.InfoWindow({
                content: ennistymon1ContentString
            });


			/*===================================
        Click Events for Markers
      ===================================*/

            // Ennis Community College
            google.maps.event.addListener(marker, 'click', function() {
				ennisInfowindow.open(carawebsMap,marker); // Reference the info window and marker
            });

            // Ennistymon CBS
            google.maps.event.addListener(marker2, 'click', function() {
				ennistymon1InfoWindow.open(carawebsMap,marker2);
            });

		}

		google.maps.event.addDomListener(window, "load", initialize);
		google.maps.event.addDomListener(window, "resize", function() {
			 var center = carawebsMap.getCenter();
			 google.maps.event.trigger(carawebsMap, "resize");
			 carawebsMap.setCenter(center);
        });

comments powered by Disqus