Published on: 23 Oct, 2017

How to get driving directions in Google Map using Javascript?

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>
<title>How to get a Google Map Driving Direction using Javascript.</title>
<script src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="googlemap.js"></script>
<link href="style.css" type="text/css" rel="stylesheet"/>
<table class="tbl-entry">
		<td>Starting Point</td>
		<td><input type="text" id="txtStartingPoint" class="input-entry"/></td>
		<td>Destination Point</td>
		<td><input type="text" id="txtDestinationPoint" class="input-entry"/></td>
		<td><input type="button" id="btnQuery" value="Query" onclick="bytutorialMap.getGeolocationData()"/> <input type="button" id="btnClear" value="Clear" onclick="bytutorialMap.clearEntries()"/> </td>

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


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


	padding:5px 10px;



table.tbl-map td{



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("");

		//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) {
		  origin: start,
		  destination: end,
		  travelMode: 'DRIVING'
		}, function(response, status) {
		  if (status === 'OK') {
		  } 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) {
				} 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 = [];
				var geoData = {
					latitude: response[0],
					longitude: response[0].geometry.location.lng()
				return bytutorialMap.codeAddress($("#txtDestinationPoint").val()).then(function(response){
					var geoData2 = {
						latitude: response[0],
						longitude: response[0].geometry.location.lng()
				bytutorialMap.initNavigateMap("map", "panel-direction", geoAddress[0].latitude, geoAddress[0].longitude, geoAddress[1].latitude, geoAddress[1].longitude);
			alert("Please enter both addresses");
	//clear entries and map display
	clearEntries: function(){
		$("#txtStartingPoint, #txtDestinationPoint").val("");
		$("#map, #panel-direction").html("");


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.



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
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.
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?
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.
12 Dec, 2018
Hi Badri, The google map on this page is working fine. Do you have any error in the javascript?
27 Oct, 2018
never mind. it has worked. it was just few things which i changed
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.
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.