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 know the driving route directions from source to destination using HTML5 and Javascript. Many travelling and other organizations that want to show route directions, travelling time, total distance on their application web page can easily implement using Google driving route API. This is more familiar and ideal for visitors. Driving route direction shows the step by step optimized driving directions for your drive using Google Map API. I hope, you have experience on google map to get directions from your location point to 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

For showing google map on our web page, we need to generate Google API Key. For this, 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 on 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 search button over the map, after that we are using 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

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


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




General Knowledge

listen
listen
listen
listen
listen
listen
listen
listen
listen


Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 27

    Best AI Startups In India

    Artificial Intelligence is a process of making an intelligent computer machine that does tasks intelligently...

  • Jan 23

    Most in demand programming languages for 2019

    In this article, we have mentioned the analyzed results of the most in demand programming language for 2019...

  • Jan 15

    Web Robots

    Web robots is an internet robot or simply crawlers, or spiders and do not relate this with hardware robots...

  • Jan 12

    Most in demand NoSQL databases software for 2019

    In this article, we have mentioned the analyzed result of most in demand NoSQL database softwares for 2019...

  • Jan 10

    Kotlin : Android App Development Choice

    Kotlin is a general-purpose open-source programming language. It runs on the JVM and its syntax is much like Java...

Follow us

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


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