Stiern

via Ad Packs

How to Use Directions with Google Maps API V3

NOTE: This article is old, and the methods to insert directions have changed — this probably won’t work.

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.

[ad#ad]

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

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:

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.

var directionDisplay;

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

directionsDisplay = new google.maps.DirectionsRenderer();

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

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:

	var contentString = '
<div id="content">'+
	'
<div id="siteNotice">'+
	'</div>
'+
	'
<h1 id="firstHeading" class="firstHeading">Høgenhaug</h1>
'+
	'
<div id="bodyContent">'+
	'
 
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.
 
'+
	'
 
Find your way here from:
 
'+
	'
<form action="index.html">'+
	'
<input id="start" type="text" 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:

	'
<form action="index.html">'+
	'
<input id="start" type="text" 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:

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?

29 comments

Leave one yourself

  1. Hello Peter,

    Can you advise me how to get direction with many marker? We would like to use these maps for school outings for our local grade school. In these way we can better setup our route.

    Thank you much

  2. how to put value inside the marker after getting the direction result

  3. how to clear previous route?

  4. Hej Peter,

    Efter som jeg kan se du er dansker, har jeg valgt at skrive på dansk. ;-)

    Efter at have prøvet mig frem og tilbage, kan jeg slet ikke få det til at virke. Har både prøvet at kopiere alt din kode og prøvet med kode andet steds fra. Kan du eventuelt opdatere guiden eller give mig et lille hint?

  5. Hi there,

    I am stuck again with another problem. I know that there are issues with printing the map, but has any one figured out how to print a map from the webpage you are displaying the map on.

    regards,
    adrian

  6. Alright,

    So I figured that out.

    Add the following line after you have defined your map variable.
    directionsDisplay.setPanel(document.getElementById(“directions_panel”));

    Now go to the body section of the document and add the following in a place you would like to display verbal directions:

    Whoever tries this, please let me know if you have any problems.

    Regards,
    Adrian

  7. Hey Peter,

    That was an awesome tutorial, followed it to the T and got everything to work fine.

    I was wondering if there is a way to actually get the directions in a verbose manner, like is there a way to display some text on the web page which will tell the user what direction they should follow precisely.

    Thanks ,
    Adrian

  8. Hi peter, thanks for posting this tutorial – very helpful! However, I’m completely stuck on how to bring this function into my current map here – http://www.hickeyspharmacies.ie/pharmacylocations_directions.html There are multiple locations and i’ve added the form code to the Cork location (bottom left of the map) but it doesn’t seem to be working – just re-loading the page. I haven’t got much experience working with Googlemaps so any assistance would be appreciated.
    Thanks a million, Tanya

  9. Thank you very much . It can help me to get direction in 2 marker ..
    and Can you advise me how to get direction in many marker ? It about traveling salesman problem . If you can , please reply me how to get it :) thank you

  10. 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);
    }
    });
    }

  11. 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

  12. 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.

    1. Please let me know if you are able to change the markers of start and end points in Directions google map. I really need it to be done in next 1 day.

  13. 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

    1. Forget it! I solved both situations.
      Thanks again for your nice work ;-)

      1. Miguel,
        Please post your solution, i’ve got the same problem.
        Thanks!
        Robert

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

  15. 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

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

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

    1. So What

      You must be an ace in user friendliness

  18. 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

    1. Hi Alan,
      Glad you could use the article, and good luck with the web development!

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

Trackbacks

  1. [...] I would like to have a small form inside the infowindow, where a visitor can enter his address and a route from him to me is being calculated and displayed. Just like this: http://stiern.com/tutorials/how-to-use-directions-with-google-maps-api-v3/ [...]

  2. [...] This post was mentioned on Twitter by Palle Zingmark, Peter S. Høgenhaug. Peter S. Høgenhaug said: New blog post at Stiern.com: How to Use Directions with Google Maps API V3 – http://bit.ly/3NlUbg. Please retweet and stumble! [...]

Leave a comment

Required

Required (will not be published)

or Twitter URL

Some HTML allowed. Spam is not.