etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

Driving route directions from source to destination using HTML5 and Javascript

In this article, you will learn how to get driving route directions from source to destination using HTML5 and JavaScript. Many travel agencies and other organisations that want to show route directions, travelling time, and total distance on their application web page can easily implement this using the Google driving route API. This is more familiar and ideal for visitors. The driving route direction shows the step-by-step optimized driving directions for your drive using the Google Map API. I hope you have experience using a Google map to get directions from your location point to your destination.

Here, we will learn how to include this route map driving directions on your application web page.





Driving route directions from source to destination


Get your API key

To show the Google map on our website, we need to generate a Google API Key. First, login to your gmail account, go to 'Google API Console' and follow the instructions and get your API key.



Create an HTML page and load the Google Map JavaScript API into your web page

Here is the CSS file 'style.css' to enhance the user interface.

1. style.css


	html, body {  height: 100%; margin: 0; padding: 0; }
	#map { height: 100%; }
	.controls { margin-top: 10px; border: 1px solid transparent; border-radius: 2px 0 0 2px;
		box-sizing: border-box; -moz-box-sizing: border-box; height: 32px; outline: none; 
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
	}
	#source { background-color: #EBECFC; font-family: Roboto; font-size: 15px; font-weight: 300;
		margin-left: 12px; padding: 0 11px 0 13px;  text-overflow: ellipsis;  width: 300px; border: 3px solid #462066;
	}
	#destination{ background-color: #EBECFC; font-family: Roboto; font-size: 15px; font-weight: 300;
		margin-left: 20px; padding: 0 11px 0 13px; text-overflow: ellipsis; width: 300px; border: 3px solid #462066;
	}
	#directionclick{ background-color: #462066; font-family: Roboto; font-size: 15px; color: #fff;
		font-weight: 300; margin-left: 10px; margin-top: 10px; padding: 4px; text-overflow: ellipsis; width: 100px;
	}
	#stepInfo{ background-color: #fff; font-family: Roboto; font-size: 15px;
		font-weight: 300; margin-left: 10px; margin-top: 10px; 
		text-overflow: ellipsis; width: 300px; position: absolute; top: 7px;
	}
	.routesegment {
		background: #462066 none repeat scroll 0 0;  border-radius: 5px 5px 0 0; color: #fff;
		display: inline-block;  font-size: 15px; font-weight: bold; height: 23px;
		padding: 6px; width: 290px;
	}
	#source:focus { border-color: #462066; }
	.routeinfo { height: 400px; overflow: auto; padding: 5px; font-size: 13px; }




index.php

This is the main file that we will call in the browser. This file contains two input boxes for source and destination, and a search button to get the route segments from source to destination. In this, we are using google.maps.place.SearchBox to place the source and destination input boxes and the search button over the map. After that, we use the Google map directions service to get the directions from source to destination. It is mandatory to generate the 'Google API Key' and replace 'YOUR_API_KEY' with your generated API key.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Places Searchbox</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <input id="source" class="controls" type="text" placeholder="Search location"> 
    <input id="destination" class="controls" type="text" placeholder="Enter Destination">
    <div id="icon"><input type="button" name="search" value="search" id="directionclick"/></div>
    <div id="stepInfo" style="display: none;"></div>
    <div id="map"></div>
    <script>
    function initiatlizemap() {
        var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 20.5937, lng: 78.9629},
          zoom: 7,
          mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('source');
        var searchBox = new google.maps.places.SearchBox(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        
        var inputDes = document.getElementById('destination');
        var searchDesBox = new google.maps.places.SearchBox(inputDes);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(inputDes);
        
        var searchIcon = document.getElementById('icon');
        var searchIconBox = new google.maps.places.SearchBox(searchIcon); 
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchIcon); 
        
        var stepInfo = document.getElementById('stepInfo');
        var searchIconBox = new google.maps.places.SearchBox(stepInfo); 
        map.controls[google.maps.ControlPosition.LEFT_CENTER].push(stepInfo);
        
        var places = searchBox.getPlaces();
        var placesDes = searchDesBox.getPlaces();
        var markers = [];
		
        var pointA = new google.maps.LatLng(28.5584, 77.2029),
        pointB = new google.maps.LatLng(28.6546, 77.2309),
        myOptions = {
          zoom: 7,
          center: pointA
        },
        // Instantiate a directions service.
        directionsService = new google.maps.DirectionsService,
        directionsDisplay = new google.maps.DirectionsRenderer({
          map: map
        });
        var control = document.getElementById('directionclick');
        google.maps.event.addDomListener(control, 'click', function() { 
            getMarker(directionsService, directionsDisplay, map);
        }); 
        google.maps.event.addDomListener(control, 'keyup', function(e) {
            if (e.keyCode == 13) {
             getMarker(directionsService, directionsDisplay, map);
            }
        });     
    }
	function getMarker(directionsService, directionsDisplay, map){ 
		calculateAndDisplayRoute(directionsService, directionsDisplay, map);
	}
	function calculateAndDisplayRoute(directionsService, directionsDisplay, map) {
		var startPoint = document.getElementById('source').value;
		var endPoint = document.getElementById('destination').value;
		directionsService.route({
		  origin: startPoint,
		  destination: endPoint,
		  travelMode: google.maps.TravelMode.DRIVING
		}, function(response, status) {
		  if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			showSteps(response, map);
		  } else {
			window.alert('Directions request failed due to ' + status);
		  }
		});
	}
	function showSteps(directionResult, map) {
		var markerArray = []; 
		var myRoute = directionResult.routes[0].legs[0];
		document.getElementById("stepInfo").style.display = "block";
		var text = '<div class="routesegment" ><div style="width: 80%; float:left;">Route Segment</div>
		text += '<div class="closeroute"><a onclick="closeroute()" style="color:#8dd4ff;">X</a></div></div>';
		text += '<div class="routeinfo"><div class="routedirections"><b>Duration:</b> '+myRoute.duration.text + ','
		text += '    <b>Distance:</b> ' + myRoute.distance.text+'<br/>';
		for (var i = 0; i < myRoute.steps.length; i++) {
		  var marker = markerArray[i] = markerArray[i] || new google.maps.Marker;
		  marker.setMap(map);
		  marker.setPosition(myRoute.steps[i].start_location);
		  text += myRoute.steps[i].instructions+'<br/>';
		}
		text += '</div></div>'; 
		document.getElementById('stepInfo').innerHTML = text;
	}
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initiatlizemap"
         async defer>
  </script>
  </body>
</html>




Related Articles

PHP Google oauth 2.0 login request and store logged user data in a MySQL Database
Python gmplot to add google map on a web page
Create Dynamic Pie Chart using Google API, PHP and MySQL
Google reCAPTCHA v2 in registration form using PHP
Download pdf file from database in PHP
How to insert data in CSV file using PHP
How to download doc file in PHP
PHP SplFileObject Standard Library
File upload in PHP MySQL database
How to add google map on your website with marker
How to show street view on google map
How to add multiple custom markers on google map
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
Hypertext Transfer Protocol Overview
-----------------
PHP code to send email using SMTP
-----------------
Characteristics of a Good Computer Program
-----------------
How to encrypt password in PHP
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to add multiple custom markers on google map
-----------------
How to get current directory, filename and code line number in PHP
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
How to generate QR Code in PHP
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP MYSQL Advanced Search Feature
-----------------
PHP Server Side Form Validation
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple PHP File Cache
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
To check whether a year is a leap year or not in php
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
PHP Secure User Registration with Login/logout
-----------------
Simple way to send SMTP mail using Node.js
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
Polling system using PHP, Ajax and MySql
-----------------
PHP Sending HTML form data to an Email
-----------------
Google Street View API Example
-----------------
Get Visitor\'s location and TimeZone
-----------------
SQL Injection Prevention Techniques
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Set and Get Cookies in PHP
-----------------
CSS Simple Menu Navigation Bar
-----------------
PHP Programming Error Types
-----------------
Date Timestamp Formats in PHP
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
How to add google map on your website and display address on click marker
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview


Popular Tutorials
PHP Tutorial (Basic & Advance)
MySQL Tutorial & Exercise
MongoDB Tutorial
Python Tutorial & Exercise
Kotlin Tutorial & Exercise
R Programming Tutorial
HTML Tutorial
jQuery Tutorial
NodeJS Tutorial
ExpressJS Tutorial
Theory of Computation Tutorial
Data Structure Tutorial
Javascript Tutorial






Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.