How to Use Directions with Google Maps API V3

How to Use Directions with Google Maps API V3

Google Maps are more fun when you can get directions. And now you can! The recent release of the Google Maps API adds two new classes in order to enable directions. In this article I will show you how to add an input field in an infobox and use that to render a route.

But before that, here’s how it looks when it is done:

Because of the size at the page here the infobox gets a scroll bar, but just ensure to make your map large enough, then it will not happen.

Overview

What's New?

Since my last article a couple of new features have been added to the API, as you can also read about in the changelog. The most important, in my opinion, is of course the support of directions, and that's the only function I will discuss here. Worthy to note, though — you do not have to use an API code anymore.

The support for directions is possible via two new classes, DirectionsRenderer and DirectionsService. DirectionsRenderer… Well… Renders the directions, and DirectionsService computes the actual directions. But the big question is — how do we use them?

Corrections

Before we rush into the new code, we should make some corrections in our excisting code. If you haven't read my article Adding Custom Google Maps to Your Website, do yourself a favor and do so before continuing on this one.


 

Next, look in your code where you define your markers and ensure that your values follow these rules:

1
2
3
4
5
6
7
8
var companyImage = new google.maps.MarkerImage(’images/logo.png,
new google.maps.Size(100,50), // (width, height)new google.maps.Point(0,0),new google.maps.Point(50,50) // (width/2, height)
);
var companyShadow = new google.maps.MarkerImage(’images/logo_shadow.png,new google.maps.Size(130,50), // (width, height)

new google.maps.Point(0,0),new google.maps.Point(65,50) // (width/2, height)
);

Dividing the image's width by 2 ensures that it's the bottom center point of the image that'll be used for the marker. Thanks to JM for this solution.

The Directions

So, first we have to call the DirectionsService constructor. Before your initialize(), create a new variable:

1
var directionsService = new google.maps.DirectionsService();

Next, we have to create the renderer. Right before the variable you just created, define a new variable directionDisplay. This variable is going to contain the renderer.

1
var directionDisplay;

In your initialize() function, right after the latLng variable, set the directionDisplay variable to this:

1
directionsDisplay = new google.maps.DirectionsRenderer();

Further down in your code, find the map variable (right after the settings variable. Write this:

1
directionsDisplay.setMap(map);

This renders the marker on the specified map, which in this case is map. Next, let's define what we want to write in our infobox by expanding the contentString variable:

1
2
3
4
5
6
7
8
9
10
11
12
	var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Høgenhaug</h1>'+
'<div id="bodyContent">'+
'<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>'+
'<p>Find your way here from:</p>'+
'<form action="index.html" onsubmit="calcRoute();return false;">'+
'<input type="text" id="start" value="prinsensgade 5, 9000">'+
'<input type="submit" value="Find directions"></form>'+
'</div>'+
'</div>';

Let's look a bit into the form used to ask the user for an address:

1
2
3
	'<form action="index.html" onsubmit="calcRoute();return false;">'+
'<input type="text" id="start" value="prinsensgade 5, 9000">'+
'<input type="submit" value="Find directions"></form>'+

First, we write "index.html" in our action attribute. This path should be to the file where your map is placed. In onsubmit we call the function calcRoute() (which we will define later), and next we write return false to prevent the site from reloading when the user submits the form. The next two lines should be pretty self-explainable. If you want the user to be able to enter both addresses, you can just add an extra input field called end. The value of the start field can be empty or you can write a pre-defined address.

Calculating the Route

At the very end of the initialize() function, write the following:

In the form we called the function calcRoute(). That's the one we are defining here. The first thing to do is define the two variables start and end. If you inserted an extra input field before write document.getElementById("end").value; in end instead of the coordinates.

Next, define the variable request. The attributes of this one are fairly logical, but let's explain them just in case. We define the origin of the route to our variable start, and the destination to end. Also, we define a travelmode —. This can be either DRIVING or WALKING.

Lastly, insert this code:

1
2
3
4
5
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});

This issues the actual search request, and completes the initialize() function.

Conclusion

With very little effort you can show your visitor how to get to your address directly from your website, instead of sending them to Google Maps or some other place. I hope you enjoyed the tutorial — please let me know if you have questions or suggestions. You are of course free to download the source files.

While you are here, why don't you follow me on Twitter or subscribe to the RSS feed?

Share, share, share!

Did you like this article? Please share it with your friends:
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Technorati
  • Twitter
  • email

Related posts:

  1. Adding Custom Google Maps to Your Website
  2. Enhancing Your Site with WebKit
  3. No More Invalid RSS

15 comments so far

Add one yourself

  1. DrLightman says:

    Thanks for the guide, didi you forgot to include the calcRoute() function?

    function calcRoute() {
    var start = document.getElementById(“start”).value;
    var end = document.getElementById(“end”).value;
    var request = {
    origin:start,
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(result);
    }
    });
    }

  2. Robert says:

    Hi,
    On: http://www.occ-online.nl/test_googlemaps.html i’ve placed the provided source code.
    It works great for the map and markers, but the directions(road) don’t show up.
    Could someone please help me!

    Robert

  3. Brendan says:

    Hi. Very helpful tutorial. I have a mini-site where the user enters the start-point and the end-point. Google draws the journey. Good so far.

    The markers for the start and end are A and B. Can I change these?? How?? Any help appreciated.

  4. Miguel says:

    Hi,

    Sorry I’m new on this. I tried to use your code but in the map I can’t get the direction shown as you can see:

    http://redebiz.net/site/teste/

    Besides I would like to define start and end through coordinates I take elsewere. Is it possible to have something like this?

    var wp = new Array(2);
    wp[0] = “38.7166055000891,-9.153757820129395″;
    wp[1] = “38.7126055000891,-9.163757820129395″;
    var start = wp[0];
    var end = wp[1];
    var request = {
    origin:start,
    destination:end,

    (Of course wp[0] and wp[1] have no direct values but those given by the variables).

    Thank you for your attention,

    Miguel

  5. Great tips. we will give it a try. :)

  6. touwal says:

    Merci mille fois!!!

  7. Santi says:

    thnx for this great tutorial, it has come very handy along your previous one “Adding Custom Google Maps to Your Website”. It’s very simple and straight to the point!

    I have one question though, is there any way of adding a “waypoint” between the “start” and “end” addresses when calculating a route??

    The problem is that I’ve added a map to my site, but it’s calculating the route through the wrong roads, and I’d like to set which towns and roads it should go through, to set the best path for my clients.

    I know this is possible, but I haven’t figured out how to implement it yet, as I’m no javascript expert….

    thnx in advance

  8. hudz says:

    Great tut. How do you get multiple direction in one map? (e.g. A > B > C). thanks.

  9. karunakaran says:

    tnx for the gr8 Tuto. But i can view the direction in my Browser.

  10. Peter…Thank you!! This is incredible. I have never developed a website before and our company finally had a need for one. I have spent the last several weeks at night teaching myself HTML, CSS and a little Javascript to develop our site. I borrowed some code from a friend to get a simple map on the site but I really wanted the ability for directions. Well I have it now. I just finished your tutorial and will implement the directions on the site in a few days.
    Again…Thank you!
    Alan

  11. designfollow says:

    very useful thank you

  12. Zan says:

    Damn, that is so helpfull ! Thank you for so many great tutorials ! Keep posting about google api ! ;) ;)

Trackbacks & Pingbacks