How to Draw Routes and Calculate Route Time and Distance on the Fly Using Google Map API V3

Introduction

 
This article will help you to solve the following problems:
  1. How to draw a route on the fly.
  2. How to delete a location from a route on the fly.
  3. How to swap the routes on Google Maps using an HTML table.
  4. How to calculate route distance and time with respect to speed.
I have used waypoints to draw the routes. Please note that you can use a maximum of 10 locations at a time. In this article, I have made all necessary JavaScript code comments in the "googlemap.js" JavaScript file. So I am not explaining the JavaScript code. Please download the attachment for more details about code. 
 
Procedure
 
Use the following procedure to draw a route on the fly:
  1. Run the project.
  2. Double-click on the start location on the Google map.
     
    MapAVI1.jpg
     
    Here I have chosen Mumbai as the starting location.
     
  3. You can choose the second location by double-clicking on another location on the map or drag the "B" icon to the second location.
     
    MapAVI2.jpg
     
    Here I have chosen Pune as my second location.
     
  4. You can choose another location by double-clicking on the map.
     
    MapAVI3.jpg
     
    Here I have chosen Hyderabad as my third location.
     
  5. Notice that when you click on the map, the table will automatically generate the latitude, longitude, distance and time.
  6. Toe calculate the time, you need to enter the speed in the TextBox.
Code
 
1. Initialize the map on page load
  1. //You can calculate directions (using a variety of methods of transportation) by using the DirectionsService object.    
  2. var directionsService = new google.maps.DirectionsService();    
  3. //Define a variable with all map points.    
  4. var _mapPoints = new Array();    
  5. //Define a DirectionsRenderer variable.    
  6. var _directionsRenderer = '';    
  7. //InitializeMap() function is used to initialize google map on page load.    
  8. function InitializeMap() {    
  9.     //DirectionsRenderer() is a used to render the direction    
  10.     _directionsRenderer = new google.maps.DirectionsRenderer();    
  11.     //Set the your own options for map.    
  12.     var myOptions = {    
  13.         zoom: 6,    
  14.         center: new google.maps.LatLng(21.7679, 78.8718),    
  15.         mapTypeId: google.maps.MapTypeId.ROADMAP    
  16.     };    
  17.     //Define the map.    
  18.     var map = new google.maps.Map(document.getElementById("dvMap"), myOptions);    
  19.     //Set the map for directionsRenderer    
  20.     _directionsRenderer.setMap(map);    
  21.     //Set different options for DirectionsRenderer mehtods.    
  22.     //draggable option will used to drag the route.    
  23.     _directionsRenderer.setOptions({    
  24.         draggable: true    
  25.     });    
  26.     //Add the doubel click event to map.    
  27.     google.maps.event.addListener(map, "dblclick"function (event) {    
  28.         //Check if Avg Speed value is enter.    
  29.         if ($("#txtAvgSpeed").val() == '') {    
  30.             alert("Please enter the Average Speed (km/hr).");    
  31.             $("#txtAvgSpeed").focus();    
  32.             return false;    
  33.         }    
  34.         var _currentPoints = event.latLng;    
  35.         _mapPoints.push(_currentPoints);    
  36.         getRoutePointsAndWaypoints();    
  37.     });    
  38.     //Add an event to route direction. This will fire when the direction is changed.    
  39.     google.maps.event.addListener(_directionsRenderer, 'directions_changed'function () {    
  40.         computeTotalDistanceforRoute(_directionsRenderer.directions);    
  41.     });    
  42. }   
    2. Get the route points and waypoints
    1. //getRoutePointsAndWaypoints() will help you to pass points and waypoints to drawRoute() function    
    2. function getRoutePointsAndWaypoints() {    
    3.     //Define a variable for waypoints.    
    4.     var _waypoints = new Array();    
    5.     if (_mapPoints.length > 2) //Waypoints will be come.    
    6.     {    
    7.         for (var j = 1; j < _mapPoints.length - 1; j++) {    
    8.             var address = _mapPoints[j];    
    9.             if (address !== "") {    
    10.                 _waypoints.push({    
    11.                     location: address,    
    12.                     stopover: true  //stopover is used to show marker on map for waypoints    
    13.                 });    
    14.             }    
    15.         }    
    16.         //Call a drawRoute() function    
    17.         drawRoute(_mapPoints[0], _mapPoints[_mapPoints.length - 1], _waypoints);    
    18.     } else if (_mapPoints.length > 1) {    
    19.         //Call a drawRoute() function only for start and end locations    
    20.         drawRoute(_mapPoints[_mapPoints.length - 2], _mapPoints[_mapPoints.length - 1], _waypoints);    
    21.     } else {    
    22.         //Call a drawRoute() function only for one point as start and end locations.    
    23.         drawRoute(_mapPoints[_mapPoints.length - 1], _mapPoints[_mapPoints.length - 1], _waypoints);    
    24.     }    
      3. Draw the route
       
      The following function is used to draw the route.
      1. //drawRoute() will help actual draw the route on map.    
      2.     function drawRoute(originAddress, destinationAddress, _waypoints) {    
      3.         //Define a request variable for route .    
      4.         var _request = '';    
      5.         //This is for more then two locatins    
      6.         if (_waypoints.length > 0) {    
      7.             _request = {    
      8.                 origin: originAddress,    
      9.                 destination: destinationAddress,    
      10.                 waypoints: _waypoints, //an array of waypoints    
      11.                 optimizeWaypoints: true//set to true if you want google to determine the shortest route or false to use the order specified.    
      12.                 travelMode: google.maps.DirectionsTravelMode.DRIVING    
      13.             };    
      14.         } else {    
      15.             //This is for one or two locations. Here noway point is used.    
      16.             _request = {    
      17.                 origin: originAddress,    
      18.                 destination: destinationAddress,    
      19.                 travelMode: google.maps.DirectionsTravelMode.DRIVING    
      20.             };    
      21.         }    
      22.         //This will take the request and draw the route and return response and status as output    
      23.         directionsService.route(_request, function (_response, _status) {    
      24.             if (_status == google.maps.DirectionsStatus.OK) {    
      25.                 _directionsRenderer.setDirections(_response);    
      26.             }    
      27.         });    
      28.     }   
        How to delete a location from the route on the fly
        1. If I want to delete the Pune location form the example above then I click on the "X" image button to delete the location.
           
          MapAVI4.jpg
           
        2. When you click on the "Ok" button, the "Pune" or "B" location will be deleted.
           
          MapAVI5.jpg
           
        Code
         
        1. The following is the code to delete the required location:
        1. //This will useful to delete the location    
        2.     function deleteLocation(trid) {    
        3.         if (confirm("Are you sure want to delete this location?") == true) {    
        4.             var _temPoint = new Array();    
        5.             for (var w = 0; w < _mapPoints.length; w++) {    
        6.                 if (trid != w + 1) {    
        7.                     _temPoint.push(_mapPoints[w]);    
        8.                 }    
        9.             }    
        10.             _mapPoints = new Array();    
        11.             for (var y = 0; y < _temPoint.length; y++) {    
        12.                 _mapPoints.push(_temPoint[y]);    
        13.             }    
        14.             getRoutePointsAndWaypoints();    
        15.         } else {    
        16.             return false;    
        17.         }    
        18.     }     
          2. I have called the deleteLocation() method on image click on click event.
           
          1. htmlhtml = html + "<td style=\"width: 60px;\"><img alt=\"DeleteLocation\" src=\"Images/Delete.jpg\" onclick=\"return deleteLocation(" + _htmlTrCount + ");\" /></td>";   
          How to swap the routes on Google map using HTML table
           
          1. In the example above, I have created three locations, they are Mumbai, Pune, and Hyderabad.
           
          MapAVI6.jpg
           
          2. Now I want to swap the locations, in other words, my start locations will be Hyderabad, then Pune, then Mumbai.
           
          3. Put the mouse on the third row of the table or the "Location Name: C" table row and then drag and drop to the first row, in other words the first row or "Location Name: A".
           
          MapAVI7.jpg
           
          4. So my start location is "A", in other words, Hyderabad. Now the second location will be Pune. Right now it is showing Mumbai. Do the same for Mumbai.
           
          MapAVI8.jpg
           
          Code
           
          1. The following code will help you to move the locations from the HTML table:
          1. //This will useful to swap rows the location    
          2.     function draganddrophtmltablerows() {    
          3.         var _tempPoints = new Array();    
          4.         // Initialise the first table (as before)    
          5.         $("#HtmlTable").tableDnD();    
          6.         // Initialise the second table specifying a dragClass and an onDrop function that will display an alert    
          7.         $("#HtmlTable").tableDnD({    
          8.             onDrop: function (table, row) {    
          9.                 var rows = table.tBodies[0].rows;    
          10.                 for (var q = 0; q < rows.length; q++) {    
          11.                     _tempPoints.push(_mapPoints[rows[q].id - 1]);    
          12.                 }    
          13.                 _mapPoints = new Array();    
          14.                 for (var y = 0; y < _tempPoints.length; y++) {    
          15.                     _mapPoints.push(_tempPoints[y]);    
          16.                 }    
          17.                 getRoutePointsAndWaypoints();    
          18.             }    
          19.         }); 
            2. I have used the Scripts/jquery.tablednd.js for this table swap.
             
            Calculate route distance and time with respect to speed
             
            The following procedure will calculate the route distance and time with respect to speed.
             
            1. When you create a location on the map, the distance and speed will automatically be calculated.
             
            MapAVI9.jpg
             
            2. For speed, you need to enter the "Average Speed (km/hr)" in the text box.
             
            Code
            1. //CreateHTMTable() will help you to create a dynamic html table    
            2.     function CreateHTMTable(_latlng, _distance) {    
            3.         var _Speed = $("#txtAvgSpeed").val();    
            4.         var _Time = parseInt(((_distance / 1000) / _Speed) * 60);;    
            5.         if (_htmlTrCount - 1 == 0) {    
            6.             _Time = 0;    
            7.             _distance = 0;    
            8.         }    
            9.         var html = '';    
            10.         var title = new Array("A""B""C""D""E""F""G""H""I""J""K""L""M""N""O");    
            11.         html = html + "<tr id=\"" + _htmlTrCount + "\">";    
            12.         html = html + "<td style=\"width: 80px;\">" + _htmlTrCount + "</td>";    
            13.         html = html + "<td style=\"width: 80px;\"><span id=\"Title_" + _htmlTrCount + "\">" + title[_htmlTrCount - 1] + "</span></td>";    
            14.         html = html + "<td style=\"width: 100px;\"><span id=\"lat_" + _htmlTrCount + "\">" + parent.String(_latlng).split(",")[0].substring(1, 8) + "</span></td>";    
            15.         html = html + "<td style=\"width: 100px;\"><span id=\"lng_" + _htmlTrCount + "\">" + parent.String(_latlng).split(",")[1].substring(1, 8) + "</span></td>";    
            16.         html = html + "<td style=\"width: 100px;\"><span id=\"dir_" + _htmlTrCount + "\">" + _distance + "</span></td>";    
            17.         html = html + "<td style=\"width: 70px;\"><span id=\"time_" + _htmlTrCount + "\">" + _Time + "</span></td>";    
            18.         html = html + "<td style=\"width: 60px;\"><img alt=\"DeleteLocation\" src=\"Images/Delete.jpg\" onclick=\"return deleteLocation(" + _htmlTrCount + ");\" /></td>";    
            19.         html = html + "</tr>";    
            20.         $("#HtmlTable").append(html);    
            21.         draganddrophtmltablerows();    
            22.     }   
            The following code will help you to calculate distance and speed.
            NOTE:
            1. As I already mentioned at the top of this article, I have used the waypoints to plot the route. So you can use a maximum of 10 waypoints with the free one.
            2. To better understand, download the source code in the attachment and run it to test it.
            3. I have used the Google map API v3 for this article.
            4. Please comment on this article for better improvement and I hope you enjoy the article.