Google Maps - Distance And Duration Calculation Between Places Using ASP.NET MVC And Bootstrap In Real-Time - Part Nine

Introduction

The DirectionsService in Google Maps helps us to calculate distance between source and destination and the duration it will take for travelling.

The Autocomplete widget is used to provide a type-ahead search box. It is operated by using Google API Key.
The source and destination textbox show us places.

After we put the source and the destination, then click on go button and you will get the realtime duration and distance details.

For more details , visit my blogs and articles based on Google Maps.
http://www.c-sharpcorner.com/members/satyaprakash-samantaray

Steps to be followed

Step1

As I described earlier, create a Controller action method named "DistanceCalculation" in "HomeController.cs".
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace SatyaGoogleMapBootstrapMVC.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Home/  
  13.   
  14.         public ActionResult Index()  
  15.         {  
  16.             return View();  
  17.         }  
  18.         public ActionResult Details()  
  19.         {  
  20.             return View();  
  21.         }  
  22.         public ActionResult Animate()  
  23.         {  
  24.             return View();  
  25.         }  
  26.         public ActionResult Icon()  
  27.         {  
  28.             return View();  
  29.         }  
  30.         public ActionResult Steet()  
  31.         {  
  32.             return View();  
  33.         }  
  34.         public ActionResult ModeTravel()  
  35.         {  
  36.             return View();  
  37.         }  
  38.         public ActionResult Traffic()  
  39.         {  
  40.             return View();  
  41.         }  
  42.         public ActionResult RouteColor()  
  43.         {  
  44.             return View();  
  45.         }  
  46.         public ActionResult DistanceCalculation()  
  47.         {  
  48.             return View();  
  49.         }  
  50.     }  

Then, create a View named "DistanceCalculation.cshtml".
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Goolge Map Distance Calculation";  
  3. }  
  4.   
  5. <title>@ViewBag.Title</title>  
  6.   
  7. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash'sGoolge Map Distance Calculation Using MVC and BOOTSTRAP</h2>  
  8. <meta charset="utf-8">  
  9. <meta name="viewport" content="width=device-width, initial-scale=1">  
  10. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
  11. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  
  12. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>  
  13.   
  14. <title>Places Searchbox</title>  
  15. <style>  
  16.      
  17.     #dvMap {  
  18.         height: 50%;  
  19.     }  
  20.   
  21.     .button {  
  22.         background-color: #4CAF50;  
  23.         border: none;  
  24.         color: white;  
  25.         padding: 15px 32px;  
  26.         text-align: center;  
  27.         text-decoration: none;  
  28.         display: inline-block;  
  29.         font-size: 16px;  
  30.         margin: 4px 2px;  
  31.         cursor: pointer;  
  32.     }  
  33.   
  34.     .button4 {  
  35.         border-radius: 9px;  
  36.     }  
  37.   
  38.     input[type=text], select {  
  39.         width: 40%;  
  40.         padding: 12px 20px;  
  41.         margin: 10px 0;  
  42.         display: inline-block;  
  43.         border: 1px solid #ccc;  
  44.         border-radius: 4px;  
  45.         box-sizing: border-box;  
  46.     }  
  47. </style>  
  48.   
  49.     <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkVZYQFe4YYva_g5ulymGDt9EBoVjjZJ8&libraries=places">  
  50.     </script>  
  51.         <script type="text/javascript">  
  52.             var source, destination;  
  53.             var directionsDisplay;  
  54.             var directionsService = new google.maps.DirectionsService();  
  55.             google.maps.event.addDomListener(window, 'load'function () {  
  56.                 new google.maps.places.SearchBox(document.getElementById('txtSource'));  
  57.                 new google.maps.places.SearchBox(document.getElementById('txtDestination'));  
  58.                 directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable'true });  
  59.             });  
  60.   
  61.             function GetRoute() {  
  62.                 var mumbai = new google.maps.LatLng(18.9750, 72.8258);  
  63.                 var mapOptions = {  
  64.                     zoom: 7,  
  65.                     center: mumbai  
  66.                 };  
  67.                  
  68.                   
  69.                 source = document.getElementById("txtSource").value;  
  70.                 destination = document.getElementById("txtDestination").value;  
  71.   
  72.                 var request = {  
  73.                     origin: source,  
  74.                     destination: destination,  
  75.                     travelMode: google.maps.TravelMode.DRIVING  
  76.                 };  
  77.                 directionsService.route(request, function (response, status) {  
  78.                     if (status == google.maps.DirectionsStatus.OK) {  
  79.                         directionsDisplay.setDirections(response);  
  80.                     }  
  81.                 });  
  82.   
  83.                   
  84.                 var service = new google.maps.DistanceMatrixService();  
  85.                 service.getDistanceMatrix({  
  86.                     origins: [source],  
  87.                     destinations: [destination],  
  88.                     travelMode: google.maps.TravelMode.DRIVING,  
  89.                     unitSystem: google.maps.UnitSystem.METRIC,  
  90.                     avoidHighways: false,  
  91.                     avoidTolls: false  
  92.                 }, function (response, status) {  
  93.                     if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {  
  94.                         var distance = response.rows[0].elements[0].distance.text;  
  95.                         var duration = response.rows[0].elements[0].duration.text;  
  96.                         var dvDistance = document.getElementById("dvDistance");  
  97.                         dvDistance.innerHTML = "";  
  98.                         dvDistance.innerHTML += "Distance Is: " + distance + "<br />";  
  99.                         dvDistance.innerHTML += "Duration Is:" + duration;  
  100.                         //alert(dvDistance.innerHTML);  
  101.                     } else {  
  102.                         alert("Your Request For Distance Not Available");  
  103.                     }  
  104.                 });  
  105.             }  
  106.         </script>  
  107.                                   
  108.                     <input type="text" id="txtSource" placeholder="Enter Source...." />  
  109.                        
  110.                     <input type="text" id="txtDestination" placeholder="Enter Destination...." />  
  111.                     <br />  
  112.                     <input type="button" value="Show" onclick="GetRoute()" class="button button4" />   
  113.                     <hr />  
  114.                     <div id="dvDistance" style="font-size:x-large; font-family: Arial Black; background-color: Yellow; color: Blue; text-align: center">  
  115.                     </div>                                      
  116.                    <hr />  
  117.      
  118. <footer>  
  119.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  120. </footer> 
For getting direction and route.
  1. source = document.getElementById("txtSource").value;  
  2.                 destination = document.getElementById("txtDestination").value;  
  3.   
  4.                 var request = {  
  5.                     origin: source,  
  6.                     destination: destination,  
  7.                     travelMode: google.maps.TravelMode.DRIVING  
  8.                 };  
  9.                 directionsService.route(request, function (response, status) {  
  10.                     if (status == google.maps.DirectionsStatus.OK) {  
  11.                         directionsDisplay.setDirections(response);  
  12.                     }  
  13.                 }); 
 For getting direction and route calulations.
  1. var service = new google.maps.DistanceMatrixService();  
  2.                 service.getDistanceMatrix({  
  3.                     origins: [source],  
  4.                     destinations: [destination],  
  5.                     travelMode: google.maps.TravelMode.DRIVING,  
  6.                     unitSystem: google.maps.UnitSystem.METRIC,  
  7.                     avoidHighways: false,  
  8.                     avoidTolls: false  
  9.                 }, function (response, status) {  
  10.                     if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {  
  11.                         var distance = response.rows[0].elements[0].distance.text;  
  12.                         var duration = response.rows[0].elements[0].duration.text;  
  13.                         var dvDistance = document.getElementById("dvDistance");  
  14.                         dvDistance.innerHTML = "";  
  15.                         dvDistance.innerHTML += "Distance Is: " + distance + "<br />";  
  16.                         dvDistance.innerHTML += "Duration Is:" + duration;  
  17.                         //alert(dvDistance.innerHTML);  
  18.                     } else {  
  19.                         alert("Your Request For Distance Not Available");  
  20.                     }  
  21.                 }); 
The first time the page loads a button click event without source and destination, the place will come.
  1. var mumbai = new google.maps.LatLng(18.9750, 72.8258);  
  2.                 var mapOptions = {  
  3.                     zoom: 7,  
  4.                     center: mumbai 
I have created one function and all the above mentioned code with rest named "GetRoute()".
  1. function GetRoute() {  
  2.   

Then, I have added source and destination textboxes.
  1. <input type="text" id="txtSource" placeholder="Enter Source...." />  
  2.                        
  3.  <input type="text" id="txtDestination" placeholder="Enter Destination...." /> 
I added a button control with mentioned function name "GetRoute()" in onclick event.
  1. <input type="button" value="Show" onclick="GetRoute()" class="button button4" />   
  2.                     <hr /> 
Then, I added div tag named "dvDistance" to show the distance and duration calculation between places.
  1. <div id="dvDistance" style="font-size:x-large; font-family: Arial Black; background-color: Yellow; color: Blue; text-align: center">  
  2.                     </div>  
Then, I put a condition for valid message if the source and the destination actually exist, else it throws a warning message.
  1. function (response, status) {  
  2.                     if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {  
  3.                         var distance = response.rows[0].elements[0].distance.text;  
  4.                         var duration = response.rows[0].elements[0].duration.text;  
  5.                         var dvDistance = document.getElementById("dvDistance");  
  6.                         dvDistance.innerHTML = "";  
  7.                         dvDistance.innerHTML += "Distance Is: " + distance + "<br />";  
  8.                         dvDistance.innerHTML += "Duration Is:" + duration;  
  9.                         //alert(dvDistance.innerHTML);  
  10.                     } else {  
  11.                         alert("Your Request For Distance Not Available");  
  12.                     }  
  13.                 });  
  1. else {  
  2.                         alert("Your Request For Distance Not Available");  
  3.                     } 
OUTPUT

Desktop View
 
 
 For valid data
 
 
 Invalid data because I put 'X' in the source textbox part.
 
 
 
Mobile View

For invalid data
 
 
GIF image for better undertstanding.
 
 

 
SUMMARY
  1. Calculate distance and duration calculation between places using Google API Key.
  2. How to implement it in MVC and Bootstrap.
  3. Autocomplete widget link with textboxes.