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>
Archived Comments
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.
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).
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.
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 ?
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."
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!!!
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.