Create a planner with directions using the Google Maps API

17 February 2011

View demo
A route planner on your own website is easy with a little help of the Google Maps API. You add a few lines of code to your site, change a few lines and your finished! Even for an inexperienced webmaster this is only a few minutes of work!

Update 22 november 2011: Be sure to also check out the custom marker tutorial to find yout how to add custom marker images to your map!

Update 4 september 2012: You might want to check out the more advanced directions tutorial with travel modes and waypoints!



1. Open your page code and look for the head section. This is the code between the and tags. In this section you will find the title of the page and such. You add this line of code to include Google Maps on your site. In previous versions of the Google Maps API you needed a API code, but in the new version this isn't needed anymore. That saves you a lot of time and stress!

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

2. After this line, you add this large piece of JavaScript. This is where all the magic happens. Later in the tutorial i will point out the lines that you'll need to change to customize the planner.

<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  function initialize() {
    var latlng = new google.maps.LatLng(51.764696,5.526042);
    directionsDisplay = new google.maps.DirectionsRenderer();
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    var marker = new google.maps.Marker({
      position: latlng,
      map: map,
      title:"My location"
    });
  }
  function calcRoute() {
    var start = document.getElementById("routeStart").value;
    var end = "51.764696,5.526042";
    var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>

3. Next you seek the tag in your file and change this line to this:

<body onload="initialize()">

Or, if you are using jQuery (for more advanced webmasters), you can add this piece of code just before the tag of the previous chunk of code:

$(document).ready(function(){
  initialize();
});

4. Then add these few lines of HTML to your page, somewhere between the and the tag:

<div id="map_canvas" style="width:710px; height:300px"></div>  
    <form action="" onsubmit="calcRoute();return false;" id="routeForm">
        <input type="text" id="routeStart" value="">
        <input type="submit" value="Route plannen">
    </form>
<div id="directionsPanel"></div>

5. After that you can go and customize the planner to suite your application. In the big piece of code entered earlier you'll notice two coordinates being used. This is the end location for the directions and the start location for the map to display before you enter an address. You should change this location to your own location. To get these coordinates you can use this site for example. Enter the address and the website will prompt you your coordinates. Copy/paste these numbers in your code, otherwise your route will always end up somewhere in Europe, and you don't want that :)

These are the rules you need to edit:
var latlng = new google.maps.LatLng(51.764696,5.526042);

And this one:
var end = "51.764696,5.526042";

In the beginning of the code you also find a list of options called "var myOptions". In this options is also "zoom" for the zoom level. If you lower this number the map will zoom out, and if you raise this number, the map will zoom in.

6. Lastly you can alter the piece of HTML we added where the planner is being shown. By default this displays a map, followed by an input field for the address and a submit button. Underneath this is the block where the directions will be shown. This will suite most of the applications, but you should change the dimensions of the map show by changing the width an height in this line:

<div id="map_canvas" style="width:710px; height:300px"></div>

At last i have included the whole code for you to copy/paste and play around with, and you can also download a sample here.

<html>
<head>
<title>Testpage route planner with directions</title>
  <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  function initialize() {
    var latlng = new google.maps.LatLng(51.764696,5.526042);
    directionsDisplay = new google.maps.DirectionsRenderer();
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    var marker = new google.maps.Marker({
      position: latlng,
      map: map,
      title:"My location"
    });
  }
  function calcRoute() {
    var start = document.getElementById("routeStart").value;
    var end = "51.764696,5.526042";
    var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == 'ZERO_RESULTS') {
        alert('No route could be found between the origin and destination.');
      } else if (status == 'UNKNOWN_ERROR') {
        alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
      } else if (status == 'REQUEST_DENIED') {
        alert('This webpage is not allowed to use the directions service.');
      } else if (status == 'OVER_QUERY_LIMIT') {
        alert('The webpage has gone over the requests limit in too short a period of time.');
      } else if (status == 'NOT_FOUND') {
        alert('At least one of the origin, destination, or waypoints could not be geocoded.');
      } else if (status == 'INVALID_REQUEST') {
        alert('The DirectionsRequest provided was invalid.');        
      } else {
        alert("There was an unknown error in your request. Requeststatus: nn"+status);
      }
    });
  }
  </script>
</head>
<body onload="initialize()">
  <div id="map_canvas" style="width:710px; height:300px"></div>  
  <form action="/routebeschrijving" onsubmit="calcRoute();return false;" id="routeForm">
    <input type="text" id="routeStart" value="">
    <input type="submit" value="Calculate route">
  </form>
  <div id="directionsPanel"></div>
</body>
</html>


Update 31 october 2011
I noticed in the demo that when you enter an invalid destination like 'new york' or 'sdjfskadkjf', the Google Maps API doesn't return a status "OK", but an error. The code sample doesn't do anything with the error and it looks like the code is broken. These lines display the directions when the status is "OK":

if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
}

There was no else-statement. So I added a few lines of code to fix this problem:

if (status == 'ZERO_RESULTS') {
  alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
  alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
  alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
  alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
  alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
  alert('The DirectionsRequest provided was invalid.');        
} else if (status == google.maps.DirectionsStatus.OK) {
  directionsDisplay.setDirections(response);
} else {
  if (status == 'ZERO_RESULTS') {
    alert("Could not calculate a route to or from one of your destinations.");
  } else {
    alert("There was an unknown error in your request. Requeststatus: "+status);
  }
}

Oh, and I made the demo a little nicer!

Update 22 november 2011: Be sure to also check out the custom marker tutorial to find yout how to add custom marker images to your map!

Update 4 september 2012: You can now also expand your route planner/directions with different travel modes and waypoints. Check it out!
You must have JavaScript enabled to use this form!

Leave a comment!

  1. Your mail is safe with me. It's only only used to display your Gravatar image!

62 comments

Previous Page 2 of 7 Next
  1. Gravatar

    Chris

    26 January 2015

    Thank you so much for such an easy to use tutorial! I have two questions:
    I tried adding in the jquery code: $(document).ready(function(){
    initialize();
    });
    before the tag as mentioned but that didn't seem to work - could you specify this a bit? That way I don't have to detach my page from the template to make the addition to the body tag.

    2) can you tell me what I would need to add in order to create the "print" button to print the directions and the map selectors to change from the regular map to a hybrid or satellite? I see these options in so many "get Directions" features.

    Also, to contribute a little something, in my scenario, I have a dark background for the site I have this on, so I needed to make the directions panel background white. For those that might be in the same boat, this is what I adjusted and it works like a charm:
    <div id="directionsPanel" style="width:100%; background-color:white">

  2. Gravatar

    D P Shukla

    20 January 2014

    Please provide the steps for Google Map v3 Integration,how we can use the api's of google.

  3. Gravatar

    kumma

    19 January 2014

    great tutorial....keep it up

  4. Gravatar

    Garvit

    19 December 2013

    i read and have used the code. But when i have put it on a site for temporary checking it does not show the route when clicked ???? wat do i do

    here's the link
    http://designitdevelopit.com/tfi/

  5. Gravatar

    Derick

    11 November 2013

    May I know how you can load the map in the lightbox. Your "view demo" route planner?

  6. Gravatar

    Robby Ablaze

    19 September 2013

    Thank you, your tutorial very usefull, please keep going!!!
    :D

  7. Gravatar

    Chris Hörtsch

    05 August 2013

    It works :-) Thank you!

  8. Gravatar

    Chris Hörtsch

    05 August 2013

    It works ;-) Thank you very much!

  9. Gravatar

    Fred

    04 August 2013

    Thanks a lot Johan for this V3 coding. It helped me a lot and it works perfectly OK. One last question however: It has been asked here before but the answer is not clear to me. Is it possible to show only the distance and duration time without the routetext in the directionspanel. When I use your answer you gave here before nothing happens. And can I CSS style it?
    Thanks a lot anyway...
    Fred

  10. Gravatar

    Goddy

    21 April 2013

    My Bad LOL that was your old demo just scrolled down to your updated code. Good Job :)

Previous Page 2 of 7 Next