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!

61 comments

Previous Page 1 of 7 Next
  1. Gravatar

    Shane Taylor

    15 April 2016

    Hi Johan,

    Are you available for hire to do custom google maps programming? I need some help...

    Please let me know. Thanks in advance...

  2. Gravatar

    Dries Schuddinck

    15 February 2016

    Thanks a ton! Really nice and clear piece of code!

  3. Gravatar

    Keith

    13 January 2016

    Hi there, i created a folder in filezilla as per a screenshot i can send you, with the notepad file with the code you gave as a sample and it is not working.
    Would you be able to advise on what i am doing wrong and how i could get this right?

  4. Gravatar

    Ronald

    30 October 2015

    Looks really nice !
    Will try to code it, well.... copy paste it this weekend.
    Thanks for posting this WITH an easy explanation.

  5. Gravatar

    angshu

    06 October 2015

    Very useful tutorial. Thank you very much, but I have 2 problems:
    1. When I load the page it's shown this error: "There was an unknown error in your request. Requeststatus:"
    2. When I click on the button, nothing happens and it shown the same error.

  6. Gravatar

    Steffen

    24 September 2015

    Hi Johan,

    Can you help me? how do i make a custom infobox for the end station?

    Best regards Steffen

  7. Gravatar

    Sepp

    12 June 2015

    Thanks, but please replace
    "var directionDisplay;" with "var directionsDisplay;"

    You use "directionsDisplay" in the code and not "directionDisplay".

  8. Gravatar

    Roudi

    26 May 2015

    Thank You!

    It is very helpful!

  9. Gravatar

    Tsvetelina

    10 March 2015

    Very useful tutorial. Thank you very much, but I have 2 problems:
    1. When I load the page it's shown this error: "There was an unknown error in your request. Requeststatus:"
    2. When I click on the button, nothing happens and it shown the same error.

  10. 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">

Previous Page 1 of 7 Next