Published on: 23 October, 2017

How to get driving directions in Google Map using Javascript

Posted by andy | 190 views 0 likes 0 favourites 0 comments
Tumblr Digg Google Plus

In this tutorial, you will learn how to get a Google Map Driving Direction from a starting point to a destination using JavaScript. You will also learn on how to geocoding an address into latitude and longitude.

We are going to create 3 files for this tutorial.

  • 1. Html File

    The html file will contains the screen layout that is designed for users to enter the starting point and destination point. Users will be able to perform a query of the location and clear the entries.

  • 2. Style CSS File

    The css file will be used to style the html page screen.

  • 3. Javascript File

    The javascript file contains all the functions needed to make it happen.

Let's get started with the HTML file. Below is the full code of the HTML5 file.

<!DOCTYPE html>
<html>
<head>
<title>How to get a Google Map Driving Direction using Javascript.</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=ENTER_YOUR_KEY_HERE"></script>
<script type="text/javascript" src="googlemap.js"></script>
<link href="style.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<table class="tbl-entry">
	<tr>
		<td>Starting Point</td>
		<td><input type="text" id="txtStartingPoint" class="input-entry"/></td>
	</tr>
	<tr>
		<td>Destination Point</td>
		<td><input type="text" id="txtDestinationPoint" class="input-entry"/></td>
	</tr>
	<tr>
		<td></td>
		<td><input type="button" id="btnQuery" value="Query" onclick="bytutorialMap.getGeolocationData()"/> <input type="button" id="btnClear" value="Clear" onclick="bytutorialMap.clearEntries()"/> </td>
	</tr>
</table>

<table class="tbl-map">
	<tr>
		<td><div id="map"></div></td>
		<td><div id="panel-direction"></div></td>
	</tr>
</table>

</body>
</html>

If you notice carefully on above codes under the head tag, you will notice that I have included two external javascript files. The first one is JQuery file, I found it is easier to use this script to manipulate the DOM of HTML. You can exclude this one if you want to, what you need to do is to modify any code starting with the $ (dollar sign) to use the native javascript code. The second script is the API Google Map script. You are required to enter the API Key for this script. If you do not have any Google Account, please register first. It is completely free. Once your account is registered you can get your API key on the following url.

https://developers.google.com/maps/documentation/javascript/get-api-key
When you request an API Key, you have an option to restrict the script source origin (web URL), this is actually important so that only you can use the API Key. Note: there is a limited number of uses to access the Google API. Therefore restriction is highly recommended.

This will be the css style code.

body{
	font-family:Arial;
	font-size:14px;
}

table.tbl-entry{
	padding:5px 10px;
}

.input-entry{
	padding:5px;
	border-radius:5px;
	min-width:300px;
}

table.tbl-map{
	width:100%;
}

table.tbl-map td{
	width:50%;
	vertical-align:top;
	padding:10px;
}

#map{
	height:500px;
}

#panel-direction{
	height:500px;
    overflow-x:hidden;
}

The map wrapper need to be specified the height, in this example, I hardcoded the height to 500px, feel free to change it as needed. This also applies for the panel direction which will contain the list of driving directions.

This is the javascript code.

//Init the geocoder library
var geocoder = new google.maps.Geocoder();

//array to hold the geo address
var geoAddress = [];

//function framework
bytutorialMap = {
	initNavigateMap: function (mapID, panelDirectionID, startLatitude, startLongitude, endLatitude, endLongitude) {
		var directionsDisplay = new google.maps.DirectionsRenderer;
		var directionsService = new google.maps.DirectionsService;
		
		//initialize the map
		var map = new google.maps.Map(document.getElementById(mapID), {
		  zoom: 7,
		  center: {lat: startLatitude, lng: startLongitude}
		}); 
		
		//clear the direction panel
		$("#" + panelDirectionID).html("");
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(document.getElementById(panelDirectionID));

		//prepare the latitude and longitude data
		start = startLatitude + ", " + startLongitude;
		end = endLatitude + ", " + endLongitude;
		bytutorialMap.calculateAndDisplayRoute(directionsService, directionsDisplay, start, end);
	},

	//function to get the driving route
	calculateAndDisplayRoute: function (directionsService, directionsDisplay, start, end) {
		directionsService.route({
		  origin: start,
		  destination: end,
		  travelMode: 'DRIVING'
		}, function(response, status) {
		  if (status === 'OK') {
			directionsDisplay.setDirections(response);
		  } else {
			alert('Directions request failed due to ' + status);
		  }
		});
	},

	//get geolocation based on address
	codeAddress: function (address) {
		return new Promise(function(resolve, reject){
			geocoder.geocode({ 'address': address }, function (results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					resolve(results);
				} else {
					reject(Error("Geocode for address " + address + " was not successful for the following reason: " + status));
				}
			});
		});
	},
	
	//function to get geolocation of both addresses.
	getGeolocationData: function(){
		if($("#txtStartingPoint").val() != "" && $("#txtDestinationPoint").val() != ""){
			geoAddress = [];
			bytutorialMap.codeAddress($("#txtStartingPoint").val()).then(function(response){
				var geoData = {
					latitude: response[0].geometry.location.lat(),
					longitude: response[0].geometry.location.lng()
				}
				geoAddress.push(geoData);
			}).then(function(){
				return bytutorialMap.codeAddress($("#txtDestinationPoint").val()).then(function(response){
					var geoData2 = {
						latitude: response[0].geometry.location.lat(),
						longitude: response[0].geometry.location.lng()
					}
					geoAddress.push(geoData2);
				});
				
			}).then(function(){
				bytutorialMap.initNavigateMap("map", "panel-direction", geoAddress[0].latitude, geoAddress[0].longitude, geoAddress[1].latitude, geoAddress[1].longitude);
			});
		}else{
			alert("Please enter both addresses");
		}
	},
	
	//clear entries and map display
	clearEntries: function(){
		$("#txtStartingPoint, #txtDestinationPoint").val("");
		$("#map, #panel-direction").html("");
	}
}

Screenshot

When getting the geolocation of the starting and destination address, I wrapped the return response in Promise, this is to make sure I get all the data before running the initNavigateMap function to get the driving direction. I have included the quick demo in here. If you have any question, feel free to post your comment below.

See in action.

You can see how the Google Map API works below.

Starting Point
Destination Point

Or alternatively, you can click on this demo link.

Demo Files

You can download the above code below.

Download

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.
Share your article with us and add your own google adsense account to earn extra money. Plus, you can promote a link back to your site.
Related Articles
Published on: 18 October, 2017
In this tutorial, you will learn how to access Google Analytics API using javascript. We will use Oauth2 to access user account analytics and a combination of Google Analytics version 3 to get the list of account summaries and version 4 to query the analytics accounts such as a number of visitors, sessions, bounce rates etc.
Related Tutorials