Google Maps - Traffic Signal Between Source And Destination Using Bootstrap And ASP.NET MVC

Introduction

Google Maps JavaScript API allows you to add real-time traffic information (wherever supported) to your map using the TrafficLayer object. Traffic information is refreshed frequently but not instantly. Rapid consecutive requests for the same area are unlikely to yield different results.

Google Maps API allows you to display map on your ASP.NET MVC Website.

This real time example can be implemented in an online transportation network company like Ola or Uber.

Description

The use of the DirectionsService object to fetch directions for different travel modes.

Travel modes

When you calculate the directions, you need to specify which transportation mode to use. The travel modes given below are currently supported.

  1. Driving - (Default) indicates standard driving directions, using the road network.
  2. Bicycling - It requests the bicycling directions via bicycle paths & the preferred streets.
  3. Transit - It requests the directions via public transit routes.
  4. Walking - It requests the walking directions via pedestrian paths & sidewalks.
Consult Google Maps coverage data to determine to what extent a country supports the directions. If you request the directions for a region in which the particular direction type is not available, the response will return the DirectionsStatus="ZERO_RESULTS".

Walking directions may not include clear pedestrian paths, so walking directions will return the warnings in the DirectionsResult, which you must display, if you are not using the default DirectionsRenderer.

An API is a set of methods and tools, which can be used to build the software Applications.

As defined by Google Places API, a place can be an establishment, a geographic location or a prominent point of an interest.

For better reference

For more details, visit my blogs and articles related to Google Maps.

http://www.c-sharpcorner.com/members/satyaprakash-samantaray/blogs/

Steps to be followed are given below.

Step 1

Create a Controller action method named Traffic in 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.   
  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.     }  

 Code description

Here, the Traffic Controller action method is used for to create view, which will show how to use traffic signal between the two places.

  1. public ActionResult Traffic()  
  2.         {  
  3.             return View();  
  4.         }   

Step2

Create a View named Traffic.cshtml.

Code Ref

  1. @{  
  2.     ViewBag.Title = "Satyaprakash Google Map Travelling Mode";  
  3. }  
  4.   
  5. <title>@ViewBag.Title</title>  
  6.   
  7. <h2 style="background-color: yellow; color: Blue; text-align: center; font-style: oblique; ">Satyaprakash's Google Map Travelling Mode 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. <style>  
  15.     #map {  
  16.         height: 50%;  
  17.     }  
  18.  
  19.     #Dropdown {  
  20.         top: 10px;  
  21.         left: 25%;  
  22.         z-index: 5;  
  23.         background-color: yellow;  
  24.         padding: 5px;  
  25.         border: 1px solid blue;  
  26.         text-align: center;  
  27.         font-family: 'Roboto','sans-serif';  
  28.         line-height: 30px;  
  29.         padding-left: 10px;  
  30.     }  
  31. </style>  
  32. <div id="Dropdown">  
  33.     <b style="color:blue">Mode Of Visting: </b>  
  34.     <select id="mode">  
  35.         <option value="DRIVING">By Driving</option>  
  36.         <option value="WALKING">By Walking</option>  
  37.         <option value="BICYCLING">By Bicycling</option>  
  38.         <option value="TRANSIT">Transit Or Bus Availability</option>  
  39.     </select>  
  40. </div>  
  41. <div id="map"></div>  
  42. <script>  
  43.     function initMap() {  
  44.         var directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "#FFFF38" } });  
  45.         var directionsService = new google.maps.DirectionsService;  
  46.         directionsDisplay.setOptions({ suppressMarkers: false });  
  47.         var map = new google.maps.Map(document.getElementById('map'), {  
  48.             zoom: 11,  
  49.             center: { lat: 12.9081, lng: 77.6476 }  
  50.         });  
  51.   
  52.         directionsDisplay.setMap(map);  
  53.   
  54.         var trafficLayer = new google.maps.TrafficLayer();  
  55.         trafficLayer.setMap(map);  
  56.   
  57.   
  58.         calculateAndDisplayRoute(directionsService, directionsDisplay);  
  59.         document.getElementById('mode').addEventListener('change'function () {  
  60.             calculateAndDisplayRoute(directionsService, directionsDisplay);  
  61.         });  
  62.     }  
  63.   
  64.     function calculateAndDisplayRoute(directionsService, directionsDisplay) {  
  65.         var selectedMode = document.getElementById('mode').value;  
  66.         directionsService.route({  
  67.             origin: { lat: 12.9165, lng: 77.6220 },  // Silkboard.  
  68.             destination: { lat: 12.9592, lng: 77.6974 },  // marathahalli.  
  69.   
  70.   
  71.             travelMode: google.maps.TravelMode[selectedMode]  
  72.   
  73.         }, function (response, status) {  
  74.             if (status == 'OK') {  
  75.                 directionsDisplay.setDirections(response);  
  76.             } else {  
  77.                 window.alert('Directions Query Unavailable Due To ' + status);  
  78.             }  
  79.   
  80.         });  
  81.     }  
  82. </script>  
  83.   
  84. <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkVZYQFe4YYva_g5ulymGDt9EBoVjjZJ8&callback=initMap"></script>  
  85.   
  86. <footer>  
  87.     <p style="background-color: yellow; font-weight: bold; color: blue; text-align: center; font-style: oblique; ">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  88. </footer> 
Code Description

I have added a dropdown with the modes of travelling.

  1. <div id="Dropdown">  
  2.     <b style="color:blue">Mode Of Visting: </b>  
  3.     <select id="mode">  
  4.         <option value="DRIVING">By Driving</option>  
  5.         <option value="WALKING">By Walking</option>  
  6.         <option value="BICYCLING">By Bicycling</option>  
  7.         <option value="TRANSIT">Transit Or Bus Availability</option>  
  8.     </select>  
  9. </div>  

Driving- (Default) indicates standard driving directions using the road network.
Bicycling- It requests the bicycling directions via bicycle paths & the preferred streets.
Transit-  It requests the directions via public transit routes.
Walking- It requests the walking directions via pedestrian paths & sidewalks.

You can calculate the directions (using a variety of methods of transportation) by using the DirectionsService object. This object communicates with Google Maps API Directions Service, which receives the direction requests and returns an efficient path.

You may either handle these directions results yourself or use the DirectionsRenderer object to render these results.
  1. var directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "#FFFF38" } });  
  2. var directionsService = new google.maps.DirectionsService;  

Here, I am going to change the route color manually.

  1. var directionsDisplay = new google.maps.DirectionsRenderer({ polylineOptions: { strokeColor: "#FFFF38" } });   

By default, it was blue in Google Maps. I have made it yellow.

The Directions Service can return multi-part directions, using a series of waypoints. Directions are displayed as a polyline drawing the route on a map or additionally as a series of textual description within a <div> element

Here, I called a function to calculate and show the routes.

  1. calculateAndDisplayRoute(directionsService, directionsDisplay);   

Proceed, as shown below.

  1. document.getElementById('mode').addEventListener('change'function () {  
  2.             calculateAndDisplayRoute(directionsService, directionsDisplay);  
  3.         });   

I defined and built the function here.

  1. function calculateAndDisplayRoute(directionsService, directionsDisplay) {  
  2.         var selectedMode = document.getElementById('mode').value;  
  3.         directionsService.route({  
  4.             origin: { lat: 12.9165, lng: 77.6220 },  // Silkboard.  
  5.             destination: { lat: 12.9592, lng: 77.6974 },  // marathahalli.  
  6.   
  7.   
  8.             travelMode: google.maps.TravelMode[selectedMode]  
  9.   
  10.         }, function (response, status) {  
  11.             if (status == 'OK') {  
  12.                 directionsDisplay.setDirections(response);  
  13.             } else {  
  14.                 window.alert('Directions Query Unavailable Due To ' + status);  
  15.             }  
  16.   
  17.         });  
  18.     }   

Here, with selection mode of travelling, the source and destination route will come with my specified color and along with the traffic Red mark symbol, which will come between the source and the destination.

  1. var selectedMode = document.getElementById('mode').value;  
  2. directionsService.route({  
  3.     origin: { lat: 12.9165, lng: 77.6220 },  // Silkboard.  
  4.     destination: { lat: 12.9592, lng: 77.6974 },  // marathahalli.  
  5.   
  6.   
  7.     travelMode: google.maps.TravelMode[selectedMode]  
  8.   
  9. }  

Note that JavaScript allows us to access the constant, using square brackets and a string value as its property.

  1. travelMode: google.maps.TravelMode[selectedMode]  

If any mode of option is not available between the places, the mentioned steps given below will be executed.

  1. function (response, status) {  
  2.             if (status == 'OK') {  
  3.                 directionsDisplay.setDirections(response);  
  4.             } else {  
  5.                 window.alert('Directions Query Unavailable Due To ' + status);  
  6.             }  
  7.      });   

This message will come with Zero Result status.

  1. window.alert('Directions Query Unavailable Due To ' + status);   

I have added the code to show about the traffic signal with Red mark symbol.

  1. var trafficLayer = new google.maps.TrafficLayer();  
  2. trafficLayer.setMap(map);  

Output




Source and Destination Information Window
Route color with traffic signal Red mark
Mobile view
GIF Images For Better understanding about traffic signal

Desktop view

Mobile view



What the colors and symbols mean on the legend

Traffic colors

The color code shows you the speed of the traffic on the road.

  • Green- No traffic delays.
  • Orange- Medium amount of traffic.
  • Red- Traffic delays. The darker the Red, the slower the speed of the traffic on the road.

Note

Gray or Blue lines on the map show your routes.

Traffic incident symbols

Traffic incidents include types of delays given below.

To see the details about what happened, click or tap the icon.

Note- For road closures, you will see a dotted Red line where the road is closed.

Public transit

The lines on the map show bus, subway and rail routes. To see more information and upcoming trains or buses, choose a station stop icon . To see station stops, look for transit icons like

NOTE

For Bicycling mode,The Central Silk board and Marathahalli route not found in Google Server.

For Transit mode, you can get the buses, which are available with bus no. and other details for The Central Silk board and Marathahalli route.

The traffic signal with the route is clearly visible with customized route color.

Summary

  1. What is a Google Map?
  2. Traffic Ssgnal with travelling mode.
  3. How to implement in MVC and Bootstrap.
  4. Get latest update of a traffic signal between the source and the destination.
  5. Here you can get the traffic signal with the various travelling modes.


Similar Articles