How to give dynamic driving directions to your customers

This post is more than 2 years old.

Quick Note: I added a quick edit just now to show a message while the browser tries to get your location. This was simple to do and I'm embarrassed to say I didn't remember it. Thanks go to Gregory Macke for reminding me.

I've blogged a couple times now about Google's Driving Directions API, but I thought it might be nice to provide a simple demo by itself. Something that folks could take an add to their web site in - literally - minutes. While I spent part of my weekend fighting another Google service, the Driving Directions API is incredibly powerful and simple. Something you don't see terribly often with Google's APIs. Here's a very simple example based on the idea that you just want to tell a person how to get to your store.

Let's begin with the HTML markup.


<!-- Office location -->
<p>
You can find our office at:<br/>
1907 West Pinhook Rd 
Lafayette, LA 70508-3225
</p>

<p style="display:none" id="directionsBlock">
<button id="getMeThereButton">Get Directions Here</button>
<div id="directionsPanel"></div>
</p>

I've got the address first, since, obviously, you want people to know where you are whether or not we can get the driving directions to work. In case folks are curious, that's the address of my local Starbucks. (Later today I may do a quick blog post where I examine their store finder and show how they could add this.) Notice that below the address we have a block of stuff hidden from the user. This is where the magic will happen. Ok, now let's switch to the JavaScript.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {

	//exit early if no geolocation
	if(!navigator.geolocation) return;
			
	var destinationAddress = "1907 West Pinhook Rd Lafayette, LA 70508-3225";
	
	//our generic error handler will just give a basic message
	function handleError(e){
		$("#directionsBlock").append("<p>Sorry, I wasn't able to provide driving directions to our location!</p>");
	}
	
	function gotDirections(geo){
		var directionsService = new google.maps.DirectionsService();
		var directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setPanel($("#directionsPanel")[0]);
		var youLocation = new google.maps.LatLng(geo.coords.latitude, geo.coords.longitude);
		
		var request = {
			origin:youLocation,
			destination:destinationAddress,
			travelMode: google.maps.TravelMode.DRIVING
		};
		directionsService.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				$("#directionsPanel").html("");
				directionsDisplay.setDirections(result);
			}
		});
		
	}
	
	$("#getMeThereButton").on("click", function() {
		$("#directionsPanel").html("<p>Getting your location and driving directions now. Please stand by.</p>");		
		navigator.geolocation.getCurrentPosition(gotDirections,handleError);
	});
	
	//show the button
	$("#directionsBlock").show();
	
});
</script>

So right away, the first thing I do is check for geolocation. If it isn't supported I just split town. I'm not doing anything else on the page so there isn't any point hanging around. After that I create a variable with my store address. Scroll down a bit to the click handler for my button. When fired, I do a geolocation request. Notice I have two call backs. One is for success and one is for any error. I could be specific in my error handler but i just do a vanilla message on any error. The last thing done in this block is to show the directions area I had previously hidden.

So - what happens when I click and the geolocation works? Basically I start setting up my direction services. I make one instance of the service, and one of the renderer. I'll explain why in a second. I take the geolocation result and create a longitude/latitude pair that Google can work with. Next I create my request. Notice that Google is fine with either a specific longitude/latitude or a generic address. Awesome. The final bit is to simply make the route request.

Here comes the cool part - and it's something I discovered when I was working on my last mobile application. While Google provides a very detailed driving direction response, if you just want to not worry about the data and just display it, Google can do it for you. The result is great:

And that's it. You can demo this yourself by clicking the demo button below. In theory, you could take my code and just change the address and be done. You can either view source on the demo or cut and paste below.


<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {

	//exit early if no geolocation
	if(!navigator.geolocation) return;
			
	var destinationAddress = "1907 West Pinhook Rd Lafayette, LA 70508-3225";
	
	//our generic error handler will just give a basic message
	function handleError(e){
		$("#directionsBlock").append("<p>Sorry, I wasn't able to provide driving directions to our location!</p>");
	}
	
	function gotDirections(geo){
		var directionsService = new google.maps.DirectionsService();
		var directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setPanel($("#directionsPanel")[0]);
		var youLocation = new google.maps.LatLng(geo.coords.latitude, geo.coords.longitude);
		
		var request = {
			origin:youLocation,
			destination:destinationAddress,
			travelMode: google.maps.TravelMode.DRIVING
		};
		directionsService.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(result);
			}
		});
		
	}
	
	$("#getMeThereButton").on("click", function() {
		navigator.geolocation.getCurrentPosition(gotDirections,handleError);
	});
	
	//show the button
	$("#directionsBlock").show();
	
});
</script>
</head>

<body>

<!-- Office location -->
<p>
You can find our office at:<br/>
1907 West Pinhook Rd 
Lafayette, LA 70508-3225
</p>

<p style="display:none" id="directionsBlock">
<button id="getMeThereButton">Get Directions Here</button>
<div id="directionsPanel"></div>
</p>

</body>
</html>

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by John Farrar posted on 11/14/2011 at 9:58 PM

I am wondering if this is a live product or if this could go the way like Google maps. Great to provide this but depending we would want to watch being dependent on it.

Comment 2 by Raymond Camden posted on 11/14/2011 at 9:59 PM

Um - where did Google Maps go? All they did was kill off the free service - and only for high traffic sites. It's not gone - it's just not free (but still free for probably 90% of the net).

Comment 3 by wfinley posted on 11/14/2011 at 11:11 PM

This is fun to implement (and I recently tried it on a mobile site) but a better user experience is to just link them straight to googlemaps (e.g. http://maps.google.com/maps.... The native Googlemaps interface is always going to be faster & slicker than serving text only driving directions.

Comment 4 by billy bob posted on 11/23/2011 at 1:12 AM

Stupid question - but why would you need dynamic driving directions ?

Are the directions in constant flux as they attempt to keep up with the changing location of the destination ?

Is the destination moving around town ?

Comment 5 by Raymond Camden posted on 11/23/2011 at 1:13 AM

No, but if you are at place X, and you need to get to store Y, then this code (for store Y) would tell you how to get there.

In other words, normally store Y would just say, "We are here.", but now they can say, "We are here, and hey, I know where you are - let me tell you how to get to me."

Comment 6 by Elise posted on 2/15/2013 at 10:53 AM

I used the code above and it works quite well. Thank You!! I was wondering if there is some additional code that needs to be added to close the directions once they have been viewed and also is it possible to have a button to email or text the directions once given?? Thanks for your help. A life saver!!!

Comment 7 by Raymond Camden posted on 2/15/2013 at 4:35 PM

You can wrap the directions in a div, include a button, and use a jQuery click/touch event to remove the HTML from the div.

In order to do email, you would need to integrate a back end server like ColdFusion or PHP. You can send the directions, and the email address, to the server, and the server would fire it off.