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 build the driving route directions from source to destination using HTML5 and Javascript. Driving route direction shows step by step optimized driving directions for your drive. 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 web page or app.

Driving route directions from source to destination

Get your api key

For showing google map in webpage, we need to generate Google API . For this, first login to your gmail account, go to 'Google API Console' and follow the instructions and get API key.

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

Here, we have created two files - 'style.css' and 'index.php'

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; }

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.






2. index.php
<!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 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


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



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 2019. All Rights Reserved.