Give Your Customers Driving Directions With the Google Maps API

Give Your Customers Driving Directions With the Google Maps API

Tutorial Details
  • Program: WordPress, Google Maps API
  • Version: 3.0+
  • Difficulty: Medium
  • Estimated Completion Time: 45 min

Instead of just showing your business location on a Google Map, why not offer your users the opportunity to get driving directions on the same page? No need for them to open up a new browser window and find it themselves, we can do better than that!

Using the Google Maps API within your WordPress website is a relatively simple process and we’ll explore exactly how to do it in this tutorial.

What We’ll Be Doing in This Tutorial…

  1. First we’ll set up some custom options so that we can enter information about our map in the WordPress Admin panel.
  2. Then we’ll use shortcodes to output a map container, input fields and directions container
  3. Finally we’ll write some JavaScript to initiate the Google Map

Note: We’ll be writing a fair bit of JavaScript here, but don’t worry! This is a WordPress tutorial so feel free to gloss over the JavaScript parts :)


Step 1 Create the Directory and Files

  1. Create a folder inside your theme called Map
  2. Inside this folder, create map.php
  3. Finally create map.js

Step 2 Include the map.php File

In your functions.php file (located in the root directory of your theme) – include the map.php file you created at the top.

/* functions.php */
include('map/map.php');

Step 3 Register Settings

There are 3 things that we want to be able to edit from the Admin area.

  1. The Destination. We’re going to use Longitude and Latitude values to specify the precise location of your destination (more details to follow)
  2. The infoWindow content. This is the white bubble you often see on Google Maps – we want to be able to edit the text in the bubble!
  3. Initial Zoom Level of the map – how far the map is zoomed in when the user first loads the page.

In map.php, hook into admin_init to register our settings:

function map_init() {
	register_setting('general', 'map_config_address');
	register_setting('general', 'map_config_infobox');
	register_setting('general', 'map_config_zoom');
}

add_action('admin_init', 'map_init');

Now we can set up the heading text for our section in the options page and all of the inputs we need.

function map_config_option_text() {
	echo '<p>Set Options for the Map here:</p>';
}

// Longitude, Latitude Values for the Destination
function map_config_address() {
	printf(('<input type="text" id="map_config_address" name="map_config_address" value="%s" size="50"/>'), get_option('map_config_address'));
}

// The text content for the InfoWindow Bubble
function map_config_infobox() {
	printf(('<textarea name="map_config_infobox" id="map_config_infobox" cols="30" rows="3">%s</textarea>'), get_option('map_config_infobox'));
}

// The initial Zoom Level of the map.
function map_config_zoom() {
	printf(('<input name="map_config_zoom" id="map_config_zoom" value="%s" />'), get_option('map_config_zoom'));
}

Finally we hook into admin_menu to display our settings in the WordPress Admin:

function map_config_menu() {
	add_settings_section('map_config', 'Map Configuration', 'map_config_option_text', 'general');
	add_settings_field('map_config_address', 'Address - Longitude and Latitude', 'map_config_address', 'general', 'map_config');
	add_settings_field('map_config_infobox', 'Map InfoWindow', 'map_config_infobox', 'general', 'map_config');
	add_settings_field('map_config_zoom', 'Map Zoom Level', 'map_config_zoom', 'general', 'map_config');
}
add_action('admin_menu', 'map_config_menu');

Go into your admin area, you should now see this:


Step 4 Enter Your Destination, infoWindow Text and Zoom Level

  1. Destination Address

    The Google Maps API actually accepts regular addresses such as ‘Newgate Lane, Mansfield, Nottinghamshire, UK’ – However, you’ll find that you will want to be more precise with your destination (for example, you’ll most likely want to point directly to your business and not just the street). You can use a Google Maps API V3 Sample to search for your destination. Drag the target around until you have pin-pointed your spot. When you’re happy, copy the Lat/Lng: value into the address field in the options – for example 27.52774434830308, 42.18752500000007 (just the numbers separated by the comma, no brackets or quotes!)

  2. InfoWindow Text

    Make this whatever you want. Your Business Name would be a good idea :)

  3. Zoom Level

    A good starting point is 10.

Click ‘Save Changes’ and when the page refreshes you can check that the info has been stored. It should look something like this now:


Step 5 Set Up the Shortcodes

When we are finished, we’ll have 3 elements: the Map, the Form, and the Directions – so in this tutorial I’ve decided to split them up into 3 separate shortcodes. This will allow us to change the order/placement of each item without having to modify any of our PHP code. For example, you may decide to have your directions above the map instead of below, or at the side, etc.

  1. Shortcode 1 : wpmap_map

    Here we register and enqueue the Google Maps API JavasScript file as well as our own maps.js file.

    Next we use the $output variable to store our map-container div along with some custom data attributes. ( data-map-infowindow will store the content for the infowindow and data-map-zoom will represent the initial zoom level – both of these values are returned using WordPress’s get_option function).

    Finally we return the generated HTML to be output:

    		function wpmap_map() {
    
    			wp_register_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false');
    			wp_enqueue_script('google-maps');
    
    			wp_register_script('wptuts-custom', get_template_directory_uri() . '/map/map.js', '', '', true);
    			wp_enqueue_script('wptuts-custom');
    
    			$output = sprintf(
    				'<div id="map-container" data-map-infowindow="%s" data-map-zoom="%s"></div>',
    				get_option('map_config_infobox'),
    				get_option('map_config_zoom')
    			);
    
    			return $output;
    		}
    		add_shortcode('wpmap_map', 'wpmap_map');
    		
  2. Shortcode 2 : wpmap_directions_container

    Here we simply return an empty div with an ID of dir-container. This will act as the container for the directions.

    		function wpmap_directions() {
    
    			$output = '<div id="dir-container" ></div>';
    			return $output;
    
    		}
    		add_shortcode('wpmap_directions_container', 'wpmap_directions');
    		
  3. Shortcode 3 : wpmap_directions_input

    This generates the Markup needed for our form.

    This is also where we’ll set our final custom option – the destination Address. This time, we’ll use a hidden form field to hold the Latitude/Longitude value that we entered earlier in the Admin Panel.

    		function wpmap_directions_input() {
    
    			$address_to = get_option('map_config_address');
    
    			$output = '<section id="directions" class="widget">
    						<strong>For Driving Directions, Enter your Address below :</strong><br />
    						<input id="from-input" type="text" value="" size="10"/>
    						<select class="hidden" onchange="" id="unit-input">
    							<option value="imperial" selected="selected">Imperial</option>
    							<option value="metric">Metric</option>
    						</select>
    						<input id="getDirections" type="button" value="Get Directions" onclick="WPmap.getDirections();"/>
    						<input id="map-config-address" type="hidden" value="' . $address_to . '"/>
    					</section>';
    			return $output;
    		}
    		add_shortcode('wpmap_directions_input', 'wpmap_directions_input');
    		

Now we have the shortcodes set up, you can go ahead and type them into your Contact Us page (or any page you like).

If you preview the page now, all you’ll see is the form input fields. That’s because we haven’t written our JavaScript that will initialize the Map yet and the div for the directions is currently empty.

Note: Before we dive into the JavaScript, we just need to add this to our style.css:

#map-container {
	width: 100%;
	height: 400px;
}

Step 7 Writing JavaScript to Interact With Google Maps API

Now it’s time to make the magic happen! I’ll provide a quick run-down of what we’re going to do first, then we’ll dig straight into the code.

  1. First we’re going to create an object WMmap and assign properties to it (some of which we’ll be grabbing from the markup that we created in the shortcodes)
  2. Then we’ll add a few methods to handle the functionality of the map and directions.
  3. One of these methods, init, will be responsible for loading the map and also for setting some default values such as the infoWindow text, zoom level and initial marker position (all from WordPress options)
  4. Finally we’ll set an event listener to load our map when the page is ready.

Ready?

I’ll explain each part of the code step-by-step, but don’t worry if you get lost, we’ll put it all together at the end.

Set Properties

Let’s create our object and set some properties. Here we are simply querying the DOM to retrieve the HTML elements that contain the values we need. The property names we’re using should be very clear and self-explanatory (mapContainer is obviously the Map Container, etc :))

Here we also get a couple of objects from the API that we’ll use later when we deal with Directions.

var WPmap = {

	// HTML Elements we'll use later!
	mapContainer	: document.getElementById('map-container'),
	dirContainer	: document.getElementById('dir-container'),
	toInput			: document.getElementById('map-config-address'),
	fromInput		: document.getElementById('from-input'),
	unitInput		: document.getElementById('unit-input'),

	// Google Maps API Objects
	dirService		: new google.maps.DirectionsService(),
	dirRenderer		: new google.maps.DirectionsRenderer(),
	map				: null,

	/* continues below */
}

The Methods

These are also part of our WPmap object, if you are unsure how everything ties together, be sure to check out the bottom of this tutorial to see all of the code together.

showDirections()

This is called from within another method that we’ll see later, it basically controls the insertion of the directions into the page.

/* within WPmap object */
showDirections:function (dirResult, dirStatus) {
	if (dirStatus != google.maps.DirectionsStatus.OK) {
		alert('Directions failed: ' + dirStatus);
		return;
	}

	// Show directions
	WPmap.dirRenderer.setMap(WPmap.map);
	WPmap.dirRenderer.setPanel(WPmap.dirContainer);
	WPmap.dirRenderer.setDirections(dirResult);
},

getStartLatLng()

This is called once from our init method. It will set the startLatLng property equal to a google.maps.LatLng object that we can use later. It requires that we provide it separate Latitude and Longitude values – how can we do this?

  1. In our shortcode we inserted a hidden form field that contains the Latitude & Longitude value that we set in the WordPress Admin. Then we retrieved the hidden form field and stored it in toInput. This means we can now access the value using WPmap.toInput.value
  2. However, the value we set in the form is just a string with a comma separating the numbers. To separate the values we can split the string up using .split(","). This will return an array containing the Latitude and Longitude as separate values.
  3. Now we can access each one by using the arrays index.
	/* within WPmap object */
	getStartLatLng: function () {
		var n = WPmap.toInput.value.split(",");
		WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
	},

getSelectedUnitSystem()

Because we have allowed our users to select whether they would prefer directions in Metric or Imperial, we use this method to set DirectionsUnitSystem to either METRIC or IMPERIAL.

	/* within WPmap object */
	getSelectedUnitSystem:function () {
		return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == 'metric' ?
			google.maps.DirectionsUnitSystem.METRIC :
			google.maps.DirectionsUnitSystem.IMPERIAL;
	},

getDirections()

This is the method that is called when the user clicks the Get Directions button.

  1. First we get the address that the user entered and store it in the fromStr variable.
  2. Next we set up an options object – dirRequest. This will contain the options needed to provide the Driving Directions.
    1. origin – The address that the user entered.
    2. destination – The google.maps.LatLng object containing the Latitude and Longitude values of your destination.
    3. travelMode – Here we ensure we are only retrieving Driving Directions.
    4. unitSystem – Specify which unit of measurement to use based on user’s choice.
  3. Finally, we call WPmap.dirService.route – and pass two parameters to it:
    1. dirRequest – this is the object containing our options.
    2. WPmap.showDirections – the callback function that handles the placement of the directions into the page.
	/* within WPmap object */
	getDirections:function () {

		var fromStr = WPmap.fromInput.value;

		var dirRequest = {
			origin      : fromStr,
			destination : WPmap.startLatLng,
			travelMode  : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem  : WPmap.getSelectedUnitSystem()
		};

		WPmap.dirService.route(dirRequest, WPmap.showDirections);
	},

init()

This is the method that is called when the page is loaded. It is responsible for :

  1. Initiating the map, centered on your address.
  2. Retrieving values that are needed to set the infoWindow text and the initial Zoom level.
  3. Setting a marker pin showing your address.
  4. Listening for when when a user clicks ‘Get Directions’ so that it can remove the initial Marker and infoWindow
	init:function () {

		// get the infowindow text and zoom level
		var infoWindowContent = WPmap.mapContainer.getAttribute('data-map-infowindow');
		var initialZoom       = WPmap.mapContainer.getAttribute('data-map-zoom');

		// call the method that sets WPmap.startLatLng
		WPmap.getStartLatLng();

		// setup the map.
		WPmap.map = new google.maps.Map(WPmap.mapContainer, {
			zoom      : parseInt(initialZoom),
			center    : WPmap.startLatLng,
			mapTypeId : google.maps.MapTypeId.ROADMAP
		});

		// setup the red marker pin
		marker = new google.maps.Marker({
			map       : WPmap.map,
			position  : WPmap.startLatLng,
			draggable : false
		});

		// set the infowindow content
		infoWindow = new google.maps.InfoWindow({
			content : infoWindowContent
		});
		infoWindow.open(WPmap.map, marker);

		// listen for when Directions are requested
		google.maps.event.addListener(WPmap.dirRenderer, 'directions_changed', function () {

			infoWindow.close();         //close the initial infoWindow
			marker.setVisible(false);   //remove the initial marker

		});
	}//init

};// <-- this is the end of the object.

** Optional **

If you want to display a nice message (like the one seen below) to your users after they have requested directions, just copy the code under the image into the event listener inside the init method.

Optional Thank you message:

	// Get the distance of the journey
	var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;

	// set the content of the infoWindow before we open it again.
	infoWindow.setContent('Thanks!<br /> Looks like you\'re about <strong> ' + distanceString + '</strong> away from us. <br />Directions are just below the map');

	// re-open the infoWindow
	infoWindow.open(WPmap.map, marker);

	setTimeout(function () {
		infoWindow.close()
	}, 8000); //close it after 8 seconds.

Step 8 Add the Event Listener That Will Load the Map

Are you still with me? We’ve made it all the way to end now and all that’s left to do is call the WPmap.init() method when the page loads. Add this to the bottom of map.js

google.maps.event.addDomListener(window, 'load', WPmap.init);

Putting All the JavaScript Together

We’ve covered a lot of ground here, so let’s see how it looks when it’s all put together.

var WPmap = {

	// HTML Elements we'll use later!
	mapContainer   : document.getElementById('map-container'),
	dirContainer   : document.getElementById('dir-container'),
	toInput        : document.getElementById('map-config-address'),
	fromInput      : document.getElementById('from-input'),
	unitInput      : document.getElementById('unit-input'),
	startLatLng    : null,

	// Google Maps API Objects
	dirService     : new google.maps.DirectionsService(),
	dirRenderer    : new google.maps.DirectionsRenderer(),
	map:null,

	showDirections:function (dirResult, dirStatus) {
		if (dirStatus != google.maps.DirectionsStatus.OK) {
			alert('Directions failed: ' + dirStatus);
			return;
		}

		// Show directions
		WPmap.dirRenderer.setMap(WPmap.map);
		WPmap.dirRenderer.setPanel(WPmap.dirContainer);
		WPmap.dirRenderer.setDirections(dirResult);
	},

	getStartLatLng:function () {
		var n = WPmap.toInput.value.split(",");
		WPmap.startLatLng = new google.maps.LatLng(n[0], n[1]);
	},

	getSelectedUnitSystem:function () {
		return WPmap.unitInput.options[WPmap.unitInput.selectedIndex].value == 'metric' ?
			google.maps.DirectionsUnitSystem.METRIC :
			google.maps.DirectionsUnitSystem.IMPERIAL;
	},

	getDirections:function () {

		var fromStr = WPmap.fromInput.value; //Get the postcode that was entered

		var dirRequest = {
			origin      : fromStr,
			destination : WPmap.startLatLng,
			travelMode  : google.maps.DirectionsTravelMode.DRIVING,
			unitSystem  : WPmap.getSelectedUnitSystem()
		};

		WPmap.dirService.route(dirRequest, WPmap.showDirections);
	},

	init:function () {

		// get the content
		var infoWindowContent = WPmap.mapContainer.getAttribute('data-map-infowindow');
		var initialZoom       = WPmap.mapContainer.getAttribute('data-map-zoom');

		WPmap.getStartLatLng();

		// setup the map.
		WPmap.map = new google.maps.Map(
			WPmap.mapContainer,
			{
				zoom: parseInt(initialZoom),     //ensure it comes through as an Integer
				center: WPmap.startLatLng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
		);

		// setup the red pin marker
		marker = new google.maps.Marker({
			map: WPmap.map,
			position: WPmap.startLatLng,
			draggable: false
		});

		// set the infowindow content
		infoWindow = new google.maps.InfoWindow({
			content:infoWindowContent
		});
		infoWindow.open(WPmap.map, marker);

		// listen for when Directions are requested
		google.maps.event.addListener(
			WPmap.dirRenderer,
			'directions_changed',
			function () {

				infoWindow.close();         //close the first infoWindow
				marker.setVisible(false);   //remove the first marker

				// setup strings to be used.
				var distanceString = WPmap.dirRenderer.directions.routes[0].legs[0].distance.text;

				// set the content of the infoWindow before we open it again.
				infoWindow.setContent('Thanks!<br /> Looks like you\'re about <strong> ' + distanceString + '</strong> away from us. <br />Directions are just below the map');

				// re-open the infoWindow
				infoWindow.open(WPmap.map, marker);
				setTimeout(function () {
					infoWindow.close()
				}, 8000); //close it after 8 seconds.

			}
		);
	}//init
};

google.maps.event.addDomListener(window, 'load', WPmap.init);

Tutorial Notes

  1. Be sure to research anything you don’t understand on Google’s Maps API Website
  2. When writing this tutorial, I was testing my code using the stock TwentyEleven WordPress Theme. Something was causing the arrow at the bottom of the InfoWindow on the map to display incorrectly. It’s because .entry-content img on line 857 has a max-width set. This screws up the way that Google renders the infoWindow. To fix it, enter this somewhere below it:

    			#map-container img { max-width: none; }
    		
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://whysodumb.com Abhimanyu

    Great. Just what I was looking for. But, I already have a map working in my theme.

    http://dillighoomo.com

    So, how do I integrate directions in a place page like this?

    http://dillighoomo.com/al-bake

  • Pingback: Give Your Customers Driving Directions With the Google Maps API | Qtiva

  • http://www.paulund.co.uk Paul

    Nice tutorial. A good addition to this would be to use geolocation as the default from address so the user can go from their current location.

    • Shane Osbourne
      Author

      That’s a great idea.

      :)

    • komiska

      yes, that would be THE perfection of this great tutorial! :)

      • Shane Osbourne
        Author

        Stay tuned…

        :)

  • http://www.customicondesign.com/ CUSTOM ICON DESIGN

    yeh, very good tutorial. I will use this code to my next project. Many thanks.

  • http://wpmidia.com.br Miriam de Paula

    Great post!!!! Thank you! =)

    • Shane Osbourne
      Author

      You’re welcome, glad you liked it :)

  • http://www.creativemanner.com ozgur coruhlu

    good one! It would be nice to add a current location tweak on this for mobile support.

    • Shane Osbourne
      Author

      I’ll be posting source code for this tutorial shortly, and I may update it to include this.

  • http://www.leachcreative.com Andrew

    Excellent tutorial, I needed this for one of future projects.

  • http://www.whatsthebigidea.com David Radovanovic

    A very timely tut for me. I’ve searched around though most WordPress map plugins are very heavy. A couple of questions: 1. Where is the admin will you expect to see the map configuration menu, i.e. theme settings? 2. Can this code work properly in a multi-site setup? Thanks!!

    • Shane Osbourne
      Author

      Hi David –

      You have caught me out there, I forgot to mention that the new options we created can be found under `Settings -> General`

      RE: Multi-site – If they share the same theme, you are good to go :)

  • Shane Osbourne
    Author

    Hey everyone, the source files can be found here:

    https://github.com/shakyShane/wptuts-map-directions

    • http://wp.envato.com/ Japh Thomson
      Staff

      Thanks, Shane! I’ve also added the download link to the top of the post :)

  • http://www.whatsthebigidea.com David Radovanovic

    Got everything working except that map.js can’t be found since my site is built using a child-theme;

    wp_register_script(‘wptuts-custom’, get_template_directory_uri() . ‘/map/map.js’, ”, ”, true);
    wp_enqueue_script(‘wptuts-custom’);

    is there a more portable way to reference the current theme template directory?

    • http://www.whatsthebigidea.com David Radovanovic

      get_stylesheet_directory_uri() I guess would be better?

      • http://stephenharris.info Stephen Harris

        get_stylesheet_directory_uri should be used – this returns the path the to the child theme if one is being used (or parent if not). get_template_directory_uri points always to the parent.

  • Ricardo

    Hi

    after adding the map i get the following error when trying to acess the wordpress admin area:
    “Cannot modify header information – headers already sent by ,,,,, wp-includes/pluggable.php on line 711″
    “Cannot modify header information – headers already sent by ,,,,, wp-includes/pluggable.php on line 712″
    “Cannot modify header information – headers already sent by ,,,,, wp-includes/pluggable.php on line 713″
    “Cannot modify header information – headers already sent by ,,,,, wp-includes/pluggable.php on line 714

    same error also appears when updating/changing the bubble title in the admin area.

    Can anyone help?

  • Ricardo

    update…locked out from wordpress admin area…after entering username and pass i get a white screen with about ten error messages similar to the ones i posted in the previous comment

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hi Ricardo, I’m unsure of your original issue, but to regain access to your WordPress Admin area, just rename the folder for the theme you’re using and you should be good to go. WordPress will automatically disable the theme, and thus, the code that’s causing the trouble.

      Hope that helps!

  • http://www.whatsthebigidea.com David Radovanovic

    Controlling the infoWindow size and removing the SelectedUnitSystem? BTW, here’s my attempt: http://bake.thewordpressdesigner.com/bake-shop-saugerties/

    • http://www.whatsthebigidea.com David Radovanovic
      • Shane Osbourne
        Author

        Hi David! The trick is to ‘view source’ on any of those Google maps examples. This way you can figure out what options are available to change! What are you looking to change specifically?

        • Shane Osbourne
          Author

          … and of course, learn about the API at https://developers.google.com/maps/documentation/javascript/reference

        • http://www.whatsthebigidea.com David Radovanovic

          I want to reduce the size of he infobubble so that it remains visible within the map container.

        • http://www.whatsthebigidea.com David Radovanovic

          Do I need to use this library: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/src/infobubble.js? And if so will it overwrite your infoWindow functions?

          • Shane Osbourne
            Author

            Hi David.

            Sorry for the delay in getting back to you. :)

            If you look at my source code, you’ll see that when we initiate the map, we set the map to be centred on our destination.

            WPmap.map = new google.maps.Map(
            WPmap.mapContainer,
            {
            zoom: parseInt(initialZoom),
            center: WPmap.startLatLng, // <– Map centred on your destination
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            );

            I’ve a had a look at your page – because you’re using a smaller map container, your infowindow is not fully in view. To get around this, you could hard-code a different lat/lng value so that the marker & the info window both fit in view.

            For example

            WPmap.map = new google.maps.Map(
            WPmap.mapContainer,
            {
            zoom: parseInt(initialZoom),
            center: new google.maps.LatLng(43.585867818694425, -75.28800895925298) // <– Map off-center to allow infowindow to fit in view.
            mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            );

            Play around with the Lat/Lng values to find something that works.

          • Shane Osbourne
            Author

            Sorry the code formatting didn’t work correctly there. I hope you understood what I meant :)

          • http://wp.envato.com/ Japh Thomson
            Staff

            If you wanted to try again Shane, to stop the editor eating your code, be sure to wrap it properly in <pre> tags as directed.

            e.g.
            <pre name=”code” class=”php”>
            // code here
            </pre>

            (Remembering also to replace < with &lt; and > with &gt;)

  • Ricardo

    can my comments be approved?

    • http://wp.envato.com/ Japh Thomson
      Staff

      Yes, all done. Apologies for the delay there, Ricardo!

  • http://ramfarms.com Sarah Potter

    Is there a way to have more than 1 mapped location? Ideally another custom option to enter lat and long?

    • Shane Osbourne
      Author

      Hi Sarah.

      Do you mean to have multiple markers on the map when it’s first loaded?

      • http://ramfarms.com Sarah Potter

        Hi Shane,

        That could work. But what I’m really hoping to do is to load a different map altogether on another page on the same site. Ideally creating a second shortcode (ex: [wpmap_map_2] ) that would load a secondary location.

        I added an other function ‘map_config_address2′ and settings field ‘map_config_address2′ which allowed me to have another latitude and longitude input but I’m having trouble generating a short code.

  • http://www.msswebdevelopment.com/wordpress/ marty

    Hey guys,
    I don’t know if anyone can help, I’m a newbie to wordpress but I created my own google maps before. Ive downloaded the source code, followed all of these instructions and the map does not display on my page.

    I can see the div in the source code but still does not display. I’m looking to implement the directions functionality also.

    Heres the link to my site:

    http://www.msswebdevelopment.com/wordpress/

    any help would be much appreciated, cheers.

    • Shane Osbourne
      Author

      Hi Marty.

      You have a couple of problems.

      First of all, the map container needs to have a width and height specified via CSS otherwise you’ll never see it.

      Also, 2 of the 3 short-codes are not functioning correctly on your page. Because they are not generating the correct output, it’s causing a JavaScript error that will prevent the map from loading.

      Do those two things (set the height and width of map-container & get the short-codes working correctly) and see if this helps.

      Good luck.

      • http://www.msswebdevelopment.com/wordpress/ marty

        Hi Shane,

        Thanks for the reply, I did manage to put a height and width on the map div and put a border on it to make sure the div was visible. However, the map doesn’t display at all.

        Also with the short codes I’m not sure how to find the errors, I have just downloaded the files from the link. Here is the code from the map.php

        <?php

        function map_config_option_text()
        {}

        function map_config_address(){
        printf(('’), get_option(‘map_config_address’));
        }

        function map_config_infobox()
        {
        printf((‘%s’), get_option(‘map_config_infobox’));
        }

        function map_config_zoom()
        {
        printf((”), get_option(‘map_config_zoom’));
        }

        function map_config_menu(){

        add_settings_section(‘map_config’, ‘Map Configuration’, ‘map_config_option_text’, ‘general’);
        add_settings_field(‘map_config_address’, ‘Address – Longitude and Lattitude’, ‘map_config_address’, ‘general’, ‘map_config’);
        add_settings_field(‘map_config_infobox’, ‘Map InfoWindow’, ‘map_config_infobox’, ‘general’, ‘map_config’);
        add_settings_field(‘map_config_zoom’, ‘Map Zoom Level’, ‘map_config_zoom’, ‘general’, ‘map_config’);
        }
        add_action(‘admin_menu’, ‘map_config_menu’);

        function map_init()
        {
        register_setting(‘general’, ‘map_config_address’);
        register_setting(‘general’, ‘map_config_infobox’);
        register_setting(‘general’, ‘map_config_zoom’);
        }

        add_action(‘admin_init’, ‘map_init’);

        function wpmap_map(){

        wp_register_script(‘google-maps’, ‘http://maps.google.com/maps/api/js?sensor=false’);
        wp_enqueue_script(‘google-maps’);

        wp_register_script(‘wptuts-custom’, get_template_directory_uri() . ‘/map/map.js’, ”, ”, true);
        wp_enqueue_script(‘wptuts-custom’);

        $output = sprintf((”),

        get_option(‘map_config_infobox’),
        get_option(‘map_config_zoom’)

        );
        return $output;

        }
        add_shortcode(‘wpmap_map’, ‘wpmap_map’);

        function wpmap_directions(){

        $output = ”;
        return $output;

        }
        add_shortcode(‘wpmap_directions_container’, ‘wpmap_directions’);

        function wpmap_directions_input(){

        $address_to = get_option(‘map_config_address’);

        $output = ‘
        For Driving Directions, Enter your Address below :

        Imperial
        Metric

        ‘;
        return $output;
        }
        add_shortcode(‘wpmap_directions_input’, ‘wpmap_directions_input’);

        • http://www.msswebdevelopment.com marty

          Hey,

          Might have some break through I have found a ReferenceError from the JS file saying WPmap is not defined I’l look into it but any advice would be great.

          • cjdsie

            I’m having the same issue. I’m not able to get the map to show up. It’s showing the div that the map should be in but nothing inside of it.

        • Dam

          Hi Marty / Chris!
          I know maybe it’s late, but the same happens to me.
          Could you please tell me how did you solve it? I don’t see the map…
          Thanks a lot!

  • Pingback: Use Geo Location to Give Your Customers Driving Directions | Wptuts+

  • Pingback: Use Geo Location to Give Your Customers Driving Directions | Wordpress Webdesigner

  • Pingback: Use Geo Location to Give Your Customers Driving Directions - Tutorial Barn

  • Pingback: My Stream | Use Geo Location to Give Your Customers Driving Directions | My Stream

  • Pingback: Use Geo Location to Give Your Customers Driving Directions | How to Web

  • Pingback: Wordpress Leaks » Use Geo Location to Give Your Customers Driving Directions

  • http://www.wprichsnippets.com vera

    Thanks for the tutorial.
    A quick question pls….

    can the function:

    /* functions.php */
    include(‘map/map.php’);

    be added automatically to the theme on installation of the plugin instead of adding manually to the theme’s function file?

    Thanks

    Vera

  • Alejandro Carrillo

    Hi, Shane…

    thanks for this, It’s gonna be really helpfull…

    Any way, got one question: I’m working in a e-commerce site, where the products for sale are available in different stores, so I need to use this functionality to display different maps, one for each store, so the people can enter their directions and and get their driving directions to each specific store…

    I made the script work perfect, but just for one direction… how can I make it function to allow many and different arrive adresses?

    Please, help, I really appreciate it

  • http://www.mojowill.com theMojoWill

    Is it possible to simply set imperial to default and remove the select box for the units?

  • Xenia

    Worked GREAT, thank you!

    • Shane Osbourne
      Author

      Glad you like it :)

  • Bithika

    Hello!

    Can I use the Google API outside of WordPress; in a custom site design?

    Please advise.

    Bithika

    • Shane Osbourne
      Author

      Hi Bithika,

      This particular tutorial is aimed at WordPress developers, but you can go ahead and use the Google Maps API anywhere you like.

  • Charles

    All right, but not shown on map.

    The map is shown in gray.

    Great Tutorial.

  • Himanshu Jain

    I am using thesis theme and I am unable to find any admin settings panel, hence I added the file to custom_functions.php using code:
    // Include Map
    require_once ( get_stylesheet_directory() . ‘/custom/map/map.php’ );

    Please help me…

  • Dam

    Congratulations for your job.
    I tried to do this,and everything was OK but I don’t see the map in the page. Maybe you could solve my problem in a while, aI’m fighting with this since ages…
    Thank you for this great tutorial, it’s what I was looking for time ago.

  • Efimia

    It looks amazing. Thanks a lot. One question, how can I add an “close button ( X )” after showing the directions?

  • Pingback: Map from google api | appsgoogleplus.com

  • Laura

    Thank you for this – it seems to work great.

    Just one question – do you know of a way to make this responsive? I need to do exactly this on a site, but it has to be responsive…