I previously posted on how to create a map using Google Maps version 2. Google Maps version 3 offers a lot more features to choose from.

The Google Maps 3 API has also undergone a whole lot of fundamental changes. For one thing, you no longer need a Google Maps API key to use the library, and a lot of the objects have changed completely – so much so that code written for version 2 probably won’t work in version 3.

Anyway, so now how to give directions from an origin point to a destination.

So the first thing to do is include the API link – which, if you have seen the link for version 2, you will immediately notice how much simpler it is.

We then create the map, passing it parameters for the zoom level, map type and where to centre it. In this example we have chosen to set the map type to the street map, and the location to be centred on Cape Town.

We then create a DirectionsRenderer object, and set it’s map to use our map we created, and assign it an HTML element to render to. This object does all the hard work of displaying our directions.

We then create a DirectionsService object which we will use to actually find the route to our destination.

To find the route, we pass an array of parameters to the route function of the DirectionsService object, and pass on the results to the renderer.

In the parameters we need to specify the origin and destination, in a text format, much like an address. TravelMode is the method to calculate the route, which in this case is set to DRIVING (the other option here is WALKING). The UnitSystem defines whether we use metric or imperial, but in this case I have set it to METRIC. The last parameter specifies whether we want to provide alternative routes as well.

That is all there is to it. And the results…
Google Maps Directions

>script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"<
>div id="map" style="width: 400px; height: 300px; float:left;"<>/div<
>div id="directions" style="width: 200px; height: 300px; float:right;"<>/div<
>script type="text/javascript"<
	//>![CDATA[
	var map = new google.maps.Map(document.getElementById("map"), {
		zoom: 7,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: new google.maps.LatLng(-33.917, 18.417)
	});


	var directionsRenderer = new google.maps.DirectionsRenderer();
	directionsRenderer.setMap(map);    
	directionsRenderer.setPanel(document.getElementById('directions'));

	var directionsService = new google.maps.DirectionsService();
	var request = {
	  origin: "Cape Town, South Africa", 
	  destination: "Tableview, South Africa",

	  travelMode: google.maps.DirectionsTravelMode.DRIVING,
	  unitSystem: google.maps.DirectionsUnitSystem.METRIC,
	  provideTripAlternatives: true
	};
	directionsService.route(request, function(response, status) {
	  if (status == google.maps.DirectionsStatus.OK) {
		directionsRenderer.setDirections(response);
	  } else {
		alert('Error: ' + status);
	  }
	});
	
	//]]<
>/script<
Share