Mike vs Web: the blog and projects of a web developer fascinated by the web and all its technical greatness.

How to Make a Google Map That Gives Directions

Google Maps are extremely popular. They are used to map out locations, but also to display information about those locations, weather conditions in the area, and even detailed driving directions. They can be mashed up with third party APIs like Twitter, Yelp, or any location based xml or json link found on Programmable Web.

Here’s what we are going to make: a Google Map that allows users to type in their address and the map will display driving directions to a specific location. This would be particularly useful for helping customers find a store, event, or other brick and mortar location.

HTML5 is fast becoming a standard, so we’re going to start off with a basic HTML5 template.

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
  	<title>How To Make A Google Map That Gives Directions</title>
</head>
<body>
	
</body>
</html>

The next thing we’re going to add is our Google Maps API key. This can be retrieved from the Google Maps API Signup page. Keep in mind we’re using v.3, which has been enhanced for mobile and tablet devices. I’ve had experience working with v.2 and trying to make it work properly on mobile devices is an uphill battle, so don’t use it.

Add this somewhere before the </head> tag.


<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=[insert-your-API-key-here]&amp;sensor=false"></script>

In the <body> section add our map canvas.


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

Now we need to add some javascript to get this map in there. This needs to be added somewhere before the </head> tag.

<script>
  		var directionDisplay;
		var directionsService = new google.maps.DirectionsService();
		var map;

		function initialize() {
			directionsDisplay = new google.maps.DirectionsRenderer();
			var headquarters = new google.maps.LatLng(51.0426981,-114.0737685);	
			var myOptions = {
				zoom:13,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				center: headquarters
			}
			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		 
            // Add A Marker For Our Location
			var headquartersMarker = new google.maps.Marker({
				position: headquarters,
				map: map,
				animation: google.maps.Animation.DROP, // not necessary, but looks nice 
				zIndex:99999
			});

			directionsDisplay.setMap(map);
		}
</script>

To make this load, we need to add the following to our <body> tag so it looks like this:


<body onload="initialize()">

With what we’ve created so far, you should see a Google Map. Now we need to add the form and the javascript that allows a user to type in a their address, postal code, or city.

Below the initialize() function inside the <head> tags, add the following:

// Calculate the route  
		function calcRoute() {
			var start = document.getElementById("start").value;
			var end = new google.maps.LatLng(51.0426981,-114.0737685);
			var request = {
				origin:start, 
				destination:end,
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};
		 
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				}
			});
		 
			var endMarker = new google.maps.Marker({
				position: end,
				map: map,
			});
		} 

For the form and to add some style to our demo, we will add this below the <body> tag, but above our map-canvas.

<div id="content">
		<h1>Get Me Driving Directions</h1>
		
		<div>
			<input type="text" name="start" id="start" value="Enter Address, Postal Code, City, etc." onclick="document.getElementById(this.id).value= '';" />
			<button onclick="calcRoute()">Submit</button>
			<button onclick="initialize()">Reset</button>
		</div>
</div><!-- #content -->	

We now have an input box and 2 buttons. Submit will calculate the route to our headquarters and reset will set the map to it original status. In the input box, I have left a small script to reset the value upon clicking it. It makes things much easier for the user and looks professional.

For presentation’s sake, here is some CSS and a link to the Google Fonts API, love Google Fonts, to add above the javascript.

<link href='http://fonts.googleapis.com/css?family=Redressed' rel='stylesheet' type='text/css'>
  
  	<!-- CSS -->
	<style>
		* { 
			margin: 0; 
			padding: 0; 
		}
		body {
			padding:20px;
			font-family: helvetica, arial, sans-serif;
		}
		h1 {
			color:#fff;
			font-family: 'Redressed', cursive;
			line-height: 130%;
		}
		#content {
			padding:20px 0 20px 20px;
			background: #000;
		}
		#map_canvas {
			width: 100%;
			height: 500px;
		}
		#start {
			padding: 6px;
			width: 260px;
			color: #000;
		}
		button {
			width: 80px;
			height: 29px;
			border: none;
			color: #fff;
			cursor: pointer;
			background: #ccc;
		}
		button:hover {
			color: #000;
			background: #eee;
		}
  	</style>

Here is what the complete code should look like:

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
  	<title>How To Make A Google Map That Gives Directions</title>
  	<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=[insert-your-API-key-here]&amp;sensor=false"></script>
  	
  	<link href='http://fonts.googleapis.com/css?family=Redressed' rel='stylesheet' type='text/css'>
  
  	<!-- CSS -->
	<style>
		* { 
			margin: 0; 
			padding: 0; 
		}
		body {
			padding:20px;
			font-family: helvetica, arial, sans-serif;
		}
		h1 {
			color:#fff;
			font-family: 'Redressed', cursive;
			line-height: 130%;
		}
		#content {
			padding:20px 0 20px 20px;
			background: #000;
		}
		#map_canvas {
			width: 100%;
			height: 500px;
		}
		#start {
			padding: 6px;
			width: 260px;
			color: #000;
		}
		button {
			width: 80px;
			height: 29px;
			border: none;
			color: #fff;
			cursor: pointer;
			background: #ccc;
		}
		button:hover {
			color: #000;
			background: #eee;
		}
  	</style>
  
  	<!-- Javascript -->
  	<script>
  		var directionDisplay;
		var directionsService = new google.maps.DirectionsService();
		var map;

		function initialize() {
			directionsDisplay = new google.maps.DirectionsRenderer();
			var headquarters = new google.maps.LatLng(51.0426981,-114.0737685);	
			var myOptions = {
				zoom:13,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				center: headquarters
			}
			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		 
			// Add A Marker For Our Headquarters 
			var headquartersMarker = new google.maps.Marker({
				position: headquarters,
				map: map,
				animation: google.maps.Animation.DROP,
				zIndex:99999
			});
		 
			directionsDisplay.setMap(map);
		}

		// Calculate the route  
		function calcRoute() {
			var start = document.getElementById("start").value;
			var end = new google.maps.LatLng(51.0426981,-114.0737685);
			var request = {
				origin:start, 
				destination:end,
				travelMode: google.maps.DirectionsTravelMode.DRIVING
			};
		 
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setDirections(response);
				}
			});
		 
			var endMarker = new google.maps.Marker({
				position: end,
				map: map,
			});
		} 
	</script>  
</head>
<body onload="initialize()">
	<div id="content">
		<h1>Get Me Driving Directions</h1>
		
		<div>
			<input type="text" name="start" id="start" value="Enter Address, Postal Code, City, etc." onclick="document.getElementById(this.id).value= '';" />
			<button onclick="calcRoute()">Submit</button>
			<button onclick="initialize()">Reset</button>
		</div>
	</div><!-- #content -->	
		
	<div id="map_canvas"></div> 
</body>
</html>

The headquarters used in this demo are the Commerx headquarters, but you will want to direct people to your own location. To use a location of your choosing, I use Get Lat Lon to retrieve latitude and longitude coordinates.

We’ve made a map that will visually deliver driving instructions to a specific location by using a few features available in Google Maps v.3. We’ve used the following functions of the API to make this possible:

There are many things that can be built by using this example. The Directions Service can supply directions for cyclists, GeoLocation could be used to make it location aware and create instructions based on where you’re standing, and you can even have it display directions in text format for someone to read to the driver.

Hope you enjoyed this article and happy coding!