Google Maps - Using ASP.NET MVC And Bootstrap In Real Time Scenario With All-In-One Features And Multiplatform Support

Introduction

The directionsService in Google Maps helps us to calculate the distance between the source and the destination. It is the duration it will take to travel and directionsDisplay in Google Maps helps us to show the route between the places.
 
Description

Autocomplete widget is required to provide a type-ahead search box. It is operated by using Google API key. The source and destination textbox will show you the places.

After putting the source and destination, click button and you will get the realtime duration and distance details with map view and route direction information.
 
For more details, refer

http://www.c-sharpcorner.com/members/satyaprakash-samantaray
 
Steps to be followed are given below.
 
Step 1
 
Create a MVC Application named SatyaGoogleMapBootstrapMVC.
 

 
Step 2
 
Create a Controller class file named HomeController.cs.
 
Code Ref
  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.         public ActionResult DistanceCalculation()  
  14.         {  
  15.             return View();  
  16.         }  
  17.     }  

Code description
 
Here, the controller action menthod is DistanceCalculation().
 
Step 3
 
Create a View named DistanceCalculation.cshtml.
 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Goolge Map With 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's Goolge Map View With Distance And Duration 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.                 map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);  
  68.                 directionsDisplay.setMap(map);  
  69.                 directionsDisplay.setPanel(document.getElementById('dvPanel'));  
  70.                  
  71.                 source = document.getElementById("txtSource").value;  
  72.                 destination = document.getElementById("txtDestination").value;  
  73.   
  74.                 var request = {  
  75.                     origin: source,  
  76.                     destination: destination,  
  77.                     travelMode: google.maps.TravelMode.DRIVING  
  78.                 };  
  79.                 directionsService.route(request, function (response, status) {  
  80.                     if (status == google.maps.DirectionsStatus.OK) {  
  81.                         directionsDisplay.setDirections(response);  
  82.                     }  
  83.                 });  
  84.   
  85.                   
  86.                 var service = new google.maps.DistanceMatrixService();  
  87.                 service.getDistanceMatrix({  
  88.                     origins: [source],  
  89.                     destinations: [destination],  
  90.                     travelMode: google.maps.TravelMode.DRIVING,  
  91.                     unitSystem: google.maps.UnitSystem.METRIC,  
  92.                     avoidHighways: false,  
  93.                     avoidTolls: false  
  94.                 }, function (response, status) {  
  95.                     if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {  
  96.                         var distance = response.rows[0].elements[0].distance.text;  
  97.                         var duration = response.rows[0].elements[0].duration.text;  
  98.                         var dvDistance = document.getElementById("dvDistance");  
  99.                         dvDistance.innerHTML = "";  
  100.                         dvDistance.innerHTML += "Distance Is: " + distance + "<br />";  
  101.                         dvDistance.innerHTML += "Duration Is:" + duration;  
  102.                          
  103.                     } else {  
  104.                         alert("Your Request For Distance Not Available");  
  105.                     }  
  106.                 });  
  107.             }  
  108.         </script>  
  109.                                   
  110.                     <input type="text" id="txtSource" placeholder="Enter Source...." />  
  111.                        
  112.                     <input type="text" id="txtDestination" placeholder="Enter Destination...." />  
  113.                     <br />  
  114.                     <input type="button" value="Show" onclick="GetRoute()" class="button button4" />   
  115.                     <hr />  
  116.                     <div id="dvDistance" style="font-size:x-large; font-family: Arial Black; background-color: Yellow; color: Blue; text-align: center">  
  117.                     </div>     
  118.                     <div id="dvMap">  
  119.                     </div>  
  120.                     <div id="dvPanel">  
  121.                     </div>                                   
  122.                     <hr />  
  123.      
  124. <footer>  
  125.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  126. </footer> 
Code description
 
To get the directions and route, proceed, as shown below. 
  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.                 });   
To get the distance and duration calculations, proceed, as show below.
  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.
  1. var mumbai = new google.maps.LatLng(18.9750, 72.8258);    
  2.                 var mapOptions = {    
  3.                     zoom: 7,    
  4.                     center: mumbai   
I created one function and proceeded, as shown below.
  1. function GetRoute() {    
  2.     
  3. }   
Now, I 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 the mentioned function name GetRoute() in onclick event.
  1. <input type="button" value="Show" onclick="GetRoute()" class="button button4" />     
  2.                     <hr />   
Now, I added div tag named dvDistance to show the distance and the duration calculation between the places.
  1. <div id="dvDistance" style="font-size:x-large; font-family: Arial Black; background-color: Yellow; color: Blue; text-align: center">    
  2.                     </div>    
The condition, which I put for the valid message is the source and the destination successfully exists, else it exbhibits it through 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.                 });   
For warning part, it exhibits, as shown below.
  1. else {    
  2.                         alert("Your Request For Distance Not Available");    
  3.                     }   
I have added a div tag for the map.
  1. <div id="dvMap">    
  2.  </div>     
Subsequently, I passed the div id dvMap.
  1. map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);    
  2. directionsDisplay.setMap(map);   
Always set the map height explicitly to define the size of the div element, which contains the map.
  1. #dvMap {    
  2.         height: 50%;    
  3.     }   
I have added a div id named dvPanel.
  1. <div id="dvPanel">    
  2. </div>    
I mentioned this id in directionsDisplay.setPanel function.
  1. directionsDisplay.setPanel(document.getElementById('dvPanel'));  
HTML Markup consists of two TextBoxes, where first one is for entering the source address while the other for entering the destination address, a Button and three HTML DIVs to display the distance and duration details, plotting map and displaying the directions.
 
Inside Google Maps Window, load event handler, for the source and the destination TextBoxes, I have implemented Google Places Autocomplete TextBox. When the button is clicked, first the Map and the Directions Service is initialized to display the map and the directions in their respective HTML DIVs.
Then using the source and destination addresses from the respective TextBoxes, the details of the directions, route, distance and duration are displayed inside the respective HTML DIVs.
 
 
 
Step 4
 
Set start page.
 
Code Ref
  1. routes.MapRoute(  
  2.                name: "Default",  
  3.                url: "{controller}/{action}/{id}",  
  4.                defaults: new { controller = "Home", action = "DistanceCalculation", id = UrlParameter.Optional }  
  5.            ); 
Code description
 
Here, the Controller name is Home and Controller action method name is DistanceCalculation.
 
 
 
Output

Desktop View
 
 
 
Route Information Part is given below
 
 
 
Mobile View
 
 
 
Route information part is given below.
 
 
 
GIF image for better undertstanding is given below. 
 
 
 
Extra GIF image shows the individual parts of this Application for better undertstanding.
 
Part 1
 
 
 
Part 2
 
 
 
Part 3
 
 
 
Summary
  1. Google Maps route direction information between the source and the destination, using Google API key.
  2. How to implement in MVC and Bootstrap.
  3. Autocomplete widget link with the textboxes.
  4. Google API key link URL. 
  5. Set the message for an invalid source and the destination selection.
  6. Multiple patform view support in Google Maps app.

Up Next
    Ebook Download
    View all
    Learn
    View all