IMG-LOGO

How to get driving directions in Google Map using Javascript?

andy - 23 Oct, 2017 11080 Views 9 Comment

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

Danish Asad Khan
25 Aug, 2018
dear sir, I have gone through the complete code and executed it on my system. Everything is good but, in the direction table some of the direction images are missing correspond to the indicated direction while I was looking for the route between Aligarh to Delhi. For example the direction table says there is a turn say "left" but image that shows left turn is missing. I tried to find out the solution but could not find. So please explain it and provide a solution. Thank you
andy
26 Aug, 2018
Hi Danish, Sometimes, Google can give the wrong direction. Those directions are fetched directly from Google API. So there is nothing cannot be done here. I think you can report to Google team about this wrong direction. Hopefully, they can fix it.
hilda
27 Oct, 2018
Hi andy, I have tried to run the code on my computer and I have also changed the API Key to one i have created but when I write the starting point and destination point it does not bring the direction or even the map. What could be the problem?
badri
12 Dec, 2018
Even I am also getting the same problem. Not even map is displaying.In console I am getting you are not authorised to use this api. But my api key has authorization to access all the apis given in the code.
andy
12 Dec, 2018
Hi Badri, The google map on this page is working fine. Do you have any error in the javascript?
hilda
27 Oct, 2018
never mind. it has worked. it was just few things which i changed
Bela
18 Dec, 2018
Hi Andy, Thank you for this tutorial. WOndering if you could do one for OpenStreetMap as well, considering there are no search results for it? :) 0 records found for keyword OpenStreetMap Thank you
Rohit Pandey
01 Jan, 2019
How to implement this one route between more then two locations.
Angelica
06 Sep, 2019
Good Day Sir How this implement this into our system that have an database latitude and longnitude
Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

Google Analytics API Tutorial using JavaScript

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