Background from:
www.SubtlePatterns.com

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!



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 {
  alert("There was an unknown error in your request. Requeststatus: nn"+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!
Johan van Tongeren headshot

About the author

This post was writen by Johan van Tongeren, owner of this website. Johan is a professional frontend developer and an amateur petrolhead. This website is his personal playground which changes almost every day. More...

You must have JavaScript enabled to use this form!

Did you enjoy this post?

Please leave me some feedback!

  1. Don't worry, it's only used for gravatar. I will never ever sell your address!

11 comments

  1. gravatar

    Max


    24March2012

    Great post,
    the only thing is that in the "whole code" section you have forgot to put the
    if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    }
    and started right from the "status==zero_results"

    took me few minutes to figure out what I did wrong:)

  2. gravatar

    Rams


    12March2012

    Hero! This is EXACTLY what ive been looking for, so easybeezy explained.. just excellent!

    Dankjewel (:

  3. gravatar

    Andy


    21December2011

    Very useful, however I found that it doesn't work for some locations, in particular mine! (51.895904,-4.009375). Specifically the route planner takes me to a location about 2 km away. Identical code works perfectly with other locations & there's no problem using Google maps directly. Any suggestions very welcome.

  4. gravatar

    Johan van Tongeren


    24October2011

    Thanks for the addition, Fred! By default the locale is set to the language of the browser from the user visiting the site. You can indeed set the locale to a fixed language, but I can't recommend this because foreign users don't understand this.

  5. gravatar

    Fred


    24October2011

    Thanks for the post! Worth adding that you can choose the output language of the directions via the language parameter:

    src="http://maps.google.com/maps/api/js?sensor=false&language=nl...

    Found via (http://code.google.com/apis/maps/documentation/javascript/basics.html#Localization)


    Groetjes!

  6. gravatar

    Libby


    23October2011

    Yes, I did enjoy this post! Thanks for discussing it, now I can get back to my regularly scheduled life (i.e. fixing / researching "the next bug" :-)

  7. gravatar

    Dreamdealer


    13October2011

    I think there is some sort of logic for that "bug" that nobody understands... I found a post on Stack Overflow reporting the same bug, but sadly no answer. It does clarify that the point the map jumps to seems to be in the center of the route.

    Update:
    This seems to be a known bug in v3.5 of the Google Maps API, as can be read in this issue. On another page in a Google Group somebody suggests switching back to version v3.4 should fix the problem.

    I don't know what features will be disabled or bugs will occur when loading v3.4 instead of v3.5, but I suggest waiting for a bugfix in the latest version would be the best to do.

    The code in the tutorial always loads the latest version but when you manually load v3.4 you'll mis the newest features and bugfixes.

    So if clicking the directions isn't really necessary i would suggest waiting for a bugfix.

  8. gravatar

    Hoi Johan,


    13October2011

    I have seen that all examples on Google api pages also make this mistake.

    http://code.google.com/apis/maps/documentation/javascript/examples/directions-panel.html

  9. gravatar

    Dreamdealer


    12October2011

    Hi Eduard,

    A short translation for English visitors: when clicking a waypoint in the route desecription the map jumps to a wrong location. The map doesn't center around the waypoint.

    Thanks for pointing this out, Eduard. I'll have a look at it as soon as possible and will post my findings here. Thanks!

  10. gravatar

    Eduard


    12October2011

    Hoi Johan,
    Een leuke handleiding toch even een klein dingetje.
    Als je een eerste tussen locatie aanklickt wijzigt de kaart map naar een vreemde locatie. Heb je daar een oplossing voor ?

    Groet Eduard

  11. gravatar

    rudolf


    18July2011

    very cool, mate

    curiously, i found an example in a dutch page (harskamperdennen.nl), and then your tutorial :o]

    much appreciated, thanxs