Advertisement
  1. Code
  2. JavaScript

Turn-By-Turn Directions with the Google Maps API

Scroll to top
Read Time: 17 min

In this tutorial, we will go through the process of creating a small widget that allows users to retrieve turn-by-turn directions to a specified location. We'll be using the Google Maps API, via JavaScript, to provide this rather advanced functionality.

Final ProductFinal ProductFinal Product

Getting An API Key

The only caveat with using Google Maps is we must apply for an API key, but this is a fairly trivial process if you already have a Google/GMail account. Unfortunately due to the requirements of Google we must develop on the domain that we provide Google, i.e. we can not develop on a local server. Fortunately for us the process will be quick and we won't spend a lot of time on the live server. Also, be sure to store you API key in a safe place because I could not find a way to retrieve them once generated, though I guess you could just recreate one.

The State of Affairs

Before we dive into code let me discuss the reason behind this idea. As most developers I spend a lot of time on the web. One particular subset of websites I visit are local businesses who certainly don't have great resources to devote to web design, but hopefully the people that are developing those sites will see articles like this and realize how easy it is to include a full-featured map into any webpage. Almost any website representing a small business has a page dedicated to telling users how to locate their physical location. Often times you get a map with their location pinned on it, which doesn't help users who don't know the area. In this tutorial we are going to change that and let users enter their address and get turn-by-turn directions to any address we want.

Including the Google Maps Javascript Library

Now that the soapbox is out of way lets look into code. The first thing we need to do is include the Javascript library that contains all the Google Maps methods. Google probably generated this code when you created your API key, but that might have pointed to the version 3 API which is still in beta testing. Here is the link to the API version 2 be sure to insert your API key. We are also going to include a file, application.js that will hold our custom functions, I stored mine in a directory at the root level called js. The following code goes within the head section of your page.

1
2
<script src="http://maps.google.com/?file=api&v=2&key=INSERT_API_KEY_HERE" type="text/javascript"></script>

3
<script src="./js/application.js" type="text/javascript"></script>

The HTML Code

In the body section of our page we need some limited markup. I will briefly go over the required bits, and you can look at the source code to see the fluff I included in my demo. The first element is an empty div with an ID of map_canvas, this is the placeholder that we point the Google Maps calls to and it will generate all the map markup within that element.

1
2
<div id="map_canvas"></div>

Next I created a div to hold the organization address and the form for the user to enter their address. You can look over this code but it is pretty simple and not very hard to discern it's meeting. Be sure to look at my CSS to see how it is styled in my demo.

1
2
<div id="addresses">
3
    <div class="address-panel">
4
        <h2>Our Address</h2>
5
        <address>
6
          1450 Jayhawk Blvd #223<br />
7
          Lawrence, KS<br />
8
          66045
9
        </address>
10
    </div>
11
12
    <div class="address-panel">
13
        <h2>Your Address</h2>
14
15
        <form action="./index.php" onsubmit="overlayDirections();return false;" method="post">
16
            <div>
17
              <label for="street">Street Address</label>
18
              <input id="street" name="street_address" type="text" />
19
            </div>
20
            <div>
21
              <div class="address-form-column">
22
                <label for="city">City</label>
23
                <input id="city" name="city" type="text" />
24
              </div>
25
26
              <div class="address-form-column">
27
                <label for="state">State</label>
28
                <select id="state" name="state">
29
                  <option value="AL">Alabama</option>
30
                  <option value="AK">Alaska</option>
31
                  <option value="AZ">Arizona</option>
32
                  <option value="AR">Arkansas</option>
33
                  <option value="CA">California</option>
34
                  <option value="CO">Colorado</option>
35
                  ...
36
                </select>
37
              </div>
38
39
              <div class="address-form-column">
40
                <label for="zip">Zip Code</label>
41
                <input id="zip" name="zip_code" type="text" maxlength="5" size="5" />
42
              </div>
43
            </div>
44
45
            <div class="button">
46
              <input name="submit" type="submit" value="Get Directions" />
47
            </div>
48
        </form>
49
    </div>
50
</div>

Notice that we are submitting this page to itself this is so we can process the page using PHP if the user has JS disabled. If they have JS enabled we want to execute a function, overlayDirections() which we will take a look at a little later. The bulk of this code goes to the select box that lets the user pick their state, I've condensed it for the sake of those printing this article, but you can grab the full code from the download. Other interesting notes is we set the size and maxlength of the zip code text field to 5. The final thing to take note is that we have assigned ids and names to all of the form elements.

Bootstrapping and Declaring Variables

Alright now we can move into the meat of this tutorial, the JavaScript code. Nearly all the calls we are going to make come from the Google Maps API that we referenced earlier. Google provides excellent documentation and example code on their website so be sure to check it out. I'll try to link to relevant pages as I use them.

The first thing is while we have our HTML page open lets bootstrap the initialize function by setting onload attribute. Note: this could be done in jQuery using the $(document).ready() function.

1
2
<body onload="initialize()">

Now we are going to move in to the js/appication.js file. The very first thing we need to do is set some variables. Some code evangelist will probably hunt me down for declaring global variables, but I believe in this case we should be okay. I'll give you the code and then explain how we will use each one.

1
2
var gdir, fromAddress, toAddress;
  • gdir: holds the GDirections object used to obtain driving directions results and display them on a map and/or a text panel.
  • fromAddress: a string that holds the full address of the user.
  • toAddress: a string that holds the business/organization address

The initialize() Function

The initialize() function we called earlier will be used to create the Map on the page and place a custom marker of our location.

1
2
/*

3
**

4
* Bootstrap function to setup map and apply

5
* custom company marker

6
*/
7
function initialize() {
8
  if (GBrowserIsCompatible()) {
9
    //settings

10
    var companyMarkerImage= "./images/jayhawk.gif";
11
    var companyLatLng     = new GLatLng(38.957101, -95.251469);
12
    var companyMarkerSize = new GSize(55, 52); //width, height

13
    
14
    toAddress = "1450 Jayhawk Blvd #223 Lawrence, KS 66045";
15
16
    var defaultZoomLevel  = 13;
17
    //end settings

18
19
    //setup elements

20
    map   = new GMap2(document.getElementById("map_canvas"));
21
    gdir  = new GDirections(map, document.getElementById("directions"));
22
23
    //error handler

24
    GEvent.addListener(gdir, "error", handleErrors);
25
26
    //set company marker

27
    var companyMarker = createMarker(companyLatLng, companyMarkerImage, companyMarkerSize);
28
29
    //set map center

30
    map.setCenter(companyLatLng, defaultZoomLevel);
31
    map.addOverlay(companyMarker);
32
  }
33
}

The first thing we need to do is check if the browser is compatible with Google Maps, and for this Google provides the GBrowserIsCompatible() in their API. In essence it returns true if the browser is compatible and allows us to move into the rest of our function. I decided to abstract some of the values to variables at the top of the function so that this could easily be ported to many applications.

1
2
  //settings

3
  var companyMarkerImage= "./images/jayhawk.gif";
4
  var companyLatLng     = new GLatLng(38.957101, -95.251469);
5
  var companyMarkerSize = new GSize(55, 52); //width, height

6
  
7
  toAddress = "1450 Jayhawk Blvd #223 Lawrence, KS 66045";
8
9
  var defaultZoomLevel  = 13;
10
  //end settings

The companyMarkerImage is a string of the location of a small image we will place at our location on the map. This is something I think is a nice touch to have a custom icon to represent your business which will personalize the generic Google Map view. Next, companyLatLng holds a GLatLng object corresponding to a latitude, longitude point in the world. Don't run out and buy a GPS device to get these numbers we can use maps.google.com . In the search box type your address and when it finds the location click the Link button on the top right of the map. Scroll through the first text box in the modal window and find &sll=....

You can copy and paste those coordinates into the parameters of our GLatLng constructor. This is the point on the map where we will place our custom image. The next variable, companyMarkerSize, holds a GSize object which represents the width and height of your custom marker image. Next we set toAddress which is the address of the business. The final variable, defaultZoomLevel, just tells the map what you want the default zoom level to be ranging from 1 to 18.

1
2
  //setup elements

3
  map   = new GMap2(document.getElementById("map_canvas"));
4
  gdir  = new GDirections(map, document.getElementById("directions"));

The next line of code creates a GMap2 object. Google describes this as "the central class in the API." This loads the map data and allows us to manipulate what is shown in the map area. It takes one argument a DOM object pointing to the element containing the map, #map_canvas. Next we set gdir to hold the GDirections object. This is the interface we use to query Google Maps for directions. The constructor takes two arguments a map object and a DOM object where we want to put the turn-by-turn directions. I choose to create an empty div below #addresses called #directions.

1
2
  //error handler

3
  GEvent.addListener(gdir, "error", handleErrors);

When using web services we always run the risk of getting an error returned. We can make this as pain free as possible using the GEvent class. In this bit of code we are saying that if we have an error getting the directions to execute a custom callback function, handleErrors in our case. We directly call the addListener() function which registers a callback. It takes 3 arguments a source object, a string referring to the type of event we want to execute the callback on, and a handler which points to a function we want executed. The function, handleErrors, is something we will look at later.

1
2
  //set company marker

3
  var companyMarker = createMarker(companyLatLng, companyMarkerImage, companyMarkerSize);
4
  
5
  //set map center

6
  map.setCenter(companyLatLng, defaultZoomLevel);
7
  map.addOverlay(companyMarker);

The last few lines in initialize() are used to create our custom marker, I chose a Jayhawk found on KU's homepage. createMarker is a wrapper function I wrote to abstract the code required to create a custom marker. It takes three arguments: a reference to a GLatLng object where we want to place the image on the, a string respresenting the path to an image, and a reference to a GSize object that represents the size of the image. Next we use the setCenter() method of the GMap2 class which takes two arguments a GLatLng object of the coordinates to center on, and an integer for the zoom level. Notice we are passing in the variables we set in the settings block at the top of the initialize() function. The final line of code uses the addOverlay() method. This is what actually adds the custom image to the map.

The initialize() function does a lot of heavy lifting, but it certainly can show for it. After we write the createMarker() function next you will be able to load up the application and see some progress. But first lets recap the initialize() function.

The createMarker() Function

Next we will create a wrapper function that takes all the pain out of creating a marker with a custom image. The reason I choose to abstract this is because it is an involved process and would clutter up our initialize() function even more. Another added benefit is that we can add multiple markers very quickly without repeating a lot of code.

1
2
/*

3
**

4
* Wrapper function to create/return a marker object

5
* with custom image

6
*/
7
function createMarker(latlng, imageURL, imageSize)
8
{
9
10
    var marker      = new GIcon(G_DEFAULT_ICON, imageURL);
11
    marker.iconSize = imageSize;
12
13
    return new GMarker(latlng, { icon: marker });
14
15
}

Considerably smaller than our first function, but just as important. First we declare a new variable, marker, and store a GIcon object. It can take two arguments copy which is a GIcon object that it will copy properties from, and image which is a string representing a path to a custom image. G_DEFAULT_ICON is a constant that represents a default marker, and the imageURL comes from the settings block in initialize(). We only have to set one more property, iconSize which is of type GSize, this represents the size of our custom image and also comes from the settings block. The final line of code returns a GMarker object which takes two arguments latlng, and icon. The first, latlng is a reference to the GLatLng object we declared in the settings block. The next argument is for the GIcon object we just created. That is all we need to do for the map portion of our application to work. You can now load up the page and see how easy it is to get a nice map on our website.

Adding Directions

This is by far my favorite part about this tutorial, allowing users to enter an address and receive back a map with the route highlighted and turn-by-turn directions. Through the use of this API we can condense something that would require thousands of lines of code and an incredible amount of processing resources to just a handful of code.

1
2
/*

3
**

4
* Looks up the directions, overlays route on map,

5
* and prints turn-by-turn to #directions.

6
*/
7
8
function overlayDirections()
9
{
10
    fromAddress =
11
      document.getElementById("street").value
12
      + " " + document.getElementById("city").value
13
      + " " + document.getElementById("state").options[document.getElementById("state").selectedIndex].value
14
      + " " + document.getElementById("zip").value;
15
16
    gdir.load("from: " + fromAddress + " to: " + toAddress);
17
}

The first line I have actually extended into five lines for clarity. In essence this grabs all the values from the form and puts a space between each part. I thought this was better than asking the user to enter the whole address into a single text box because that can become confusing.

The second line makes use of the gdir we set in initialize(). We call the load() method and pass a single string argument, which is essentially what we would pass maps.google.com via the search box. The from: and to: keywords help tell Google which address needs to be the starting point and which needs to be the ending point. That is all we need to do for directions, yeah I was shocked too! If you visit your page again you can see this in action.

Handling Errors

Next we are going to declare the handleErrors() function. I grabbed this from Google Sample code on their API website. I won't go into any detail because it fairly straightforward.

1
2
  function handleErrors(){
3
     if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
4
       alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
5
     else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
6
       alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
7
     else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
8
       alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
9
     else if (gdir.getStatus().code == G_GEO_BAD_KEY)
10
       alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
11
     else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
12
       alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
13
     else alert("An unknown error occurred.");
14
  }

It has a long if...elseif...else statement that checks for many error types and alerts the user if any occur. You can modify this if you wish to make the alert less technical.

Degradable

As good web developers we should make sure our website works for as many users as possible, including those with JavaScript disabled. In this situation I chose to redirect those with JS disabled to Google Maps with the search performed so they still get directions. This is done using PHP to evaluate the form and redirect to Google Maps. At the top of your HTML page insert this code:

1
2
<?php
3
  //settings

4
5
    $TO    = "1450 Jayhawk Blvd #223 Lawrence, KS 66045"; //company address

6
7
  //end settings

8
9
  //they seem to have JS disabled, let's redirect them to

10
  //Google Maps and prefill the query

11
  if($_POST['submit']) {
12
    $FROM  = $_POST['street'] . " " . $_POST['city'] . ", " . $_POST['state'] . " " . $_POST['zip'];
13
    $LOC   = $_POST['language'];
14
15
    $url   = "http://maps.google.com/maps?hl=".urlencode($LOC)."&q=from:".urlencode($FROM)."+to:".urlencode($TO)."&ie=UTF8";
16
17
    header("Location: " . $url);
18
  }
19
?>
20
...

First we have a settings block again which only has one variable to set, $TO. This is similar to what we did in JavaScript for toAddress, but we need the same string in PHP too. Next we have an if statement to check for POSTed data which means our form was submitted. Now we grab the form values and place them in a string with spaces and store that in a variable, $FROM. Then we store the language value to $LOC, more on this later. The $url variable will hold the string representing the query URL to Google. Notice that we url-encode our values so they safely travel on the redirect. The final line of code uses PHP headers to redirect the user to Google.

Optional: Add Multi-Language Support

As a business you want to reach out to as many people as possible and part of that process is supporting multiple languages. In Google Maps supporting other languages comes at no extra cost to us.

First open up your HTML page and insert the following code between your form tags.

1
2
...
3
<select id="language" name="language">
4
  <option value="en" selected>English</option>
5
  <option value="fr">French</option>                  
6
  <option value="de">German</option>
7
  <option value="ja">Japanese</option>
8
  <option value="es">Spanish</option>
9
</select>
10
...

Of course if you want to remove any languages just delete the option tag for it, you can also change the default by moving the selected attribute.

Moving to js/application.js, we need to make just two changes. Starting in the overlayDirections() function after we create the string fromAddress add this to grab the selected value from the language select box and save it to our language variable.

1
2
...
3
var language  = document.getElementById("language").options[document.getElementById("language").selectedIndex].value;
4
...

Next, add an argument to the gdir.load() function, this takes an options set. In our case we only need to declare locale so it knows the proper language and units for the turn-by-turn directions.

1
2
...
3
gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": language });
4
...

Note: We already included this in the PHP redirect and if you want to disable this just statically set $LOC.

1
2
...
3
$LOC = 'en'
4
...

Conclusion

That is all we need for this amazing feature, and I hope you learned a bit about Google Maps along the way. I challenge you as developers to continue to find interesting ways to integrate maps in to your applications. Anytime a model is location aware, you should question if your project has a use for visual representation on a map. Thanks for reading; as always, I am here to help in the comments or on Twitter (@noahhendrix).


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.