site map

Parkside Web Development

Read... Write... Share...

August 27, 2008

Driving Directions in Google Maps API

Filed under: Developing the WebThe Quagmire @ 9:48 pm

I was just looking at the Google Map API and noticed that they added turn by turn directions since the last time I looked at it. This is really exciting news and something that I really could have used a year ago.

In this article I’m going to lay out a bare bones example of getting map directions. We’ll start with some basic HTML and CSS. Then we’ll work our way into the scripts that will drive the interface. Keep in mind that this is intended as a bare example with only the necessary elements to get things functioning. In other words… it ain’t gonna be real pretty.

First we’ll need a container for the map, directions & form.

1
2
3
4
5
6
7
8
9
10
11
<body>
<div id="frmholder"><br />
   <form onsubmit="return false;">
      From Address:<br /><input size="55" id="fromaddress" /><br /><br />
      To Address:<br /><input size="55" id="toaddress" /><br /><br />
      <input type="submit" value="Get Directions" />
      </form><br />
</div>
<div id="mapholder"></div>
<div id="dirholder"></div>
</body>

Now we’ll arrange them with a little CSS. I’m putting borders and backgrounds in so that we can see the elements while we’re building.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
body {
   background: #333;
}
form {
   margin:0;
   padding:0;
}
 
#frmholder {
   width: 701px;
   border: 1px solid #000;
   border-bottom: 0;
   text-align: center;
   background: #fff;
}
#mapholder {
   width: 500px;
   height: 500px;
   float: left;
   border: 1px solid #000;
   background: #fff;
}
#dirholder {
   width: 200px;
   float: left;
   border: 1px solid #000;
   height: 500px;
   border-left: 0;
   background: #fff;
   overflow: auto;
}

Now comes the fun part. We’ll start out by modifying our body tag to point at empty load and unload functions. We’ll also load the map API. Note that we would need to pass a key parameter with our google request to put this up online.

1
2
3
4
5
6
7
8
9
10
11
12
<script src="http://maps.google.com/maps?file=api" type="text/javascript"></script>
 
<script language="javascript">
// <![CDATA[
function setupmap() {
}
 
function teardownmap() {
}
 
// ]]>
<body onload="setupmap();" onunload="teardownmap();">

Next let’s get the map rendering and unloading. We’ll be adding to our existing load & unload functions for this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function setupmap() {
   if (GBrowserIsCompatible()) {
      // First lets setup a start point. Phoenix works.
      point = new GLatLng(33.42571077612917, -112.115478515625);
 
      // Now we initialize the map and tell it which
      // container to live in.
      map = new GMap2(document.getElementById("mapholder"));
 
      // This command adds the pan/zoom controls to the map.
      map.addControl(new GSmallMapControl());
 
      // Now we move the map to our start point and zoom
      // level 9.
      map.setCenter(point, 9);
   }
}
 
function teardownmap() {
   // This command uploads the Google Map API.
   GUnload();
}

At this point we have a basic google map. Now we’ll start plugging in our code to generate directions. First we’ll add a handler for when our form is submitted. We’re going to return false so that we don’t continue to another page.

1
<form onsubmit="getdirections();return false;">

Now we get to the meat of the direction code. I’ll include comments in the code to explain what’s going on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function getdirections() {
   // First we'll get the start and end address from our
   // form.
   var fmaddr = document.getElementById("fromaddress").value;
   var toaddr = document.getElementById("toaddress").value;
 
   // Next we'll setup a GDirections object. This is what
   // we interact with to generate the directions.
   if (!directions) {
      directions = new GDirections(map);
   }
 
   // Now we'll need to setup a listener to react when
   //  the directions are drawn on the map.
   GEvent.addListener(directions, "addoverlay", function() {
      // First we'll gather up some information about
      // the directions.
      var route = directions.getRoute(0);
 
      // This variable will help us track the boundaries
      // for all the points along our path.
      var bounds = new GLatLngBounds();
 
      // Here's a variable that we'll dump our html
      // results into.
      var disp = "";
 
      // We can start off with a header that's got our
      // distance and an approximate driving duration.
      disp = disp + "<h3>Directions</h3>"+directions.getDistance().html+" about "+directions.getDuration().html+"<br /><hr size='1' noshade='noshade' />";
 
      // We'll put our turn by turn directions into a table.
      disp = disp + "<table>";
 
      // Start looping through the turn by turn elements.
      for(i=0;i< route.getNumSteps();i++) {
         // We work with the turn by turn directions in
         // steps... One at a time.
         var stp = route.getStep(i);
 
         // We'll extend our boundaries for each step
         // so that the entire path is on our map at
         // the end.
         bounds.extend(stp.getLatLng());
 
         // I'm doing alternating colors here to make
         // it a little more readable.
         var clr = (i%2)?"#ccc":"#eee";
 
         // Here we build our table row. First we do
         // the description of the step, then we
         // display the distance.
         disp = disp + "<tr valign='top'><td style='background:"+clr+";'>" + stp.getDescriptionHtml() + "</td>";
         disp = disp + "<td style='background:"+clr+";'>" + stp.getDistance().html+"</td></tr>";
      }
      // Now we close out our table. and display
      // our results.
      disp = disp + "</table>";
      document.getElementById('dirholder').innerHTML = disp;
 
      // Now we'll change the map view port so that
      // it shows all the points in our directions.
      map.setZoom(map.getBoundsZoomLevel(bounds));
      map.setCenter(bounds.getCenter());
   });
 
   // This listener will react when either of our
   // addresses is unmapable.
   GEvent.addListener(directions, "error", function() {
      alert("Could not generate a route for the current start and end addresses");
   });
 
   // We finally arrive at the moment of truth. This
   // single line kicks off the whole process.
   directions.load("from: "+fmaddr+" to: "+toaddr, { preserveViewport: true, getSteps: true });
}

And there you have it. A bare bones example of the Google Map Directions API. I’ve posted the final html document so you can see it in action. Feel free to post any questions or comments in the… comments area below or feel free to contact us.

Share/Save/Bookmark


4 Comments »

Thanigaivelan — August 12, 2009 @ 5:26 am

Hi,

Thanks for your code. But its not working.

http://www.parksidedev.com/mapsample.html

Please check above url. its not working for the Getdirection.

Please send the correct code i need in my project.

Thanigaivelan — August 12, 2009 @ 5:38 am

Hello,

Sorry for the above post its working but if i gave full address means its not working for exampl

From Address
Military Park Building, 60 Park Place Newark, NJ 07102

To Address
231 Clarksville Road, Suite 200, Princeton Junction, NJ 08550

Means its not working.

Please tell me what i has to change

Thanks
Thanigaivelan

The Quagmire — August 12, 2009 @ 9:38 pm

I think you’ll find that using the full from address in google maps generates multiple locations. This can be handled in the javascript code, however that’s a bit beyond the scope of this blog post.

Vasan — November 18, 2009 @ 10:00 pm

Thanks a heap, this should get me going.

I did face a minor hitch, ‘if (!directions) {
‘ this line was kicking me out, then i removed the if condition and took the instance of the direction object directly without the if condition, started working like a charm. Thanks again!!

Cheers

Vasan

RSS feed for comments on this post. TrackBack URL

Leave a comment