Google Maps Drawing Distance Code
- Updated date Apr 13, 2020
- 512.6k
- 24
In this article you will learn how to draw and work with routes on the fly using the Google Maps API V3.
Introduction
This article will help you to solve the following problems:
- How to draw a route on the fly.
- How to delete a location from a route on the fly.
- How to swap the routes on Google Maps using an HTML table.
- 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:
- Run the project.
- Double-click on the start location on the Google map.
- You can choose the second location by double-clicking on another location on the map or drag the "B" icon to the second location.
- You can choose another location by double-clicking on the map.
- Notice that when you click on the map, the table will automatically generate the latitude, longitude, distance and time.
- Toe calculate the time, you need to enter the speed in the TextBox.
Code
1. Initialize the map on page load
- var directionsService = new google.maps.DirectionsService();
- var _mapPoints = new Array();
- var _directionsRenderer = '' ;
- function InitializeMap() {
- _directionsRenderer =new google.maps.DirectionsRenderer();
- var myOptions = {
- zoom: 6,
- center:new google.maps.LatLng(21.7679, 78.8718),
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var map = new google.maps.Map(document.getElementById( "dvMap" ), myOptions);
- _directionsRenderer.setMap(map);
- _directionsRenderer.setOptions({
- draggable:true
- });
- google.maps.event.addListener(map,"dblclick" , function (event) {
- if ($( "#txtAvgSpeed" ).val() == '' ) {
- alert("Please enter the Average Speed (km/hr)." );
- $("#txtAvgSpeed" ).focus();
- return false ;
- }
- var _currentPoints = event.latLng;
- _mapPoints.push(_currentPoints);
- getRoutePointsAndWaypoints();
- });
- google.maps.event.addListener(_directionsRenderer,'directions_changed' , function () {
- computeTotalDistanceforRoute(_directionsRenderer.directions);
- });
- }
2. Get the route points and waypoints
- function getRoutePointsAndWaypoints() {
- var _waypoints = new Array();
- if (_mapPoints.length > 2)
- {
- for ( var j = 1; j < _mapPoints.length - 1; j++) {
- var address = _mapPoints[j];
- if (address !== "" ) {
- _waypoints.push({
- location: address,
- stopover:true
- });
- }
- }
- drawRoute(_mapPoints[0], _mapPoints[_mapPoints.length - 1], _waypoints);
- }else if (_mapPoints.length > 1) {
- drawRoute(_mapPoints[_mapPoints.length - 2], _mapPoints[_mapPoints.length - 1], _waypoints);
- }else {
- drawRoute(_mapPoints[_mapPoints.length - 1], _mapPoints[_mapPoints.length - 1], _waypoints);
- }
- }
3. Draw the route
The following function is used to draw the route.
- function drawRoute(originAddress, destinationAddress, _waypoints) {
- var _request = '' ;
- if (_waypoints.length > 0) {
- _request = {
- origin: originAddress,
- destination: destinationAddress,
- waypoints: _waypoints,
- optimizeWaypoints:true ,
- travelMode: google.maps.DirectionsTravelMode.DRIVING
- };
- }else {
- _request = {
- origin: originAddress,
- destination: destinationAddress,
- travelMode: google.maps.DirectionsTravelMode.DRIVING
- };
- }
- directionsService.route(_request,function (_response, _status) {
- if (_status == google.maps.DirectionsStatus.OK) {
- _directionsRenderer.setDirections(_response);
- }
- });
- }
How to delete a location from the route on the fly
-
If I want to delete the Pune location form the example above then I click on the "X" image button to delete the location.
-
When you click on the "Ok" button, the "Pune" or "B" location will be deleted.
Code
1. The following is the code to delete the required location:
- function deleteLocation(trid) {
- if (confirm( "Are you sure want to delete this location?" ) == true ) {
- var _temPoint = new Array();
- for ( var w = 0; w < _mapPoints.length; w++) {
- if (trid != w + 1) {
- _temPoint.push(_mapPoints[w]);
- }
- }
- _mapPoints =new Array();
- for ( var y = 0; y < _temPoint.length; y++) {
- _mapPoints.push(_temPoint[y]);
- }
- getRoutePointsAndWaypoints();
- }else {
- return false ;
- }
- }
2. I have called the deleteLocation() method on image click on click event.
- 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.
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".
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.
Code
1. The following code will help you to move the locations from the HTML table:
- function draganddrophtmltablerows() {
- var _tempPoints = new Array();
- $("#HtmlTable" ).tableDnD();
- $("#HtmlTable" ).tableDnD({
- onDrop:function (table, row) {
- var rows = table.tBodies[0].rows;
- for ( var q = 0; q < rows.length; q++) {
- _tempPoints.push(_mapPoints[rows[q].id - 1]);
- }
- _mapPoints =new Array();
- for ( var y = 0; y < _tempPoints.length; y++) {
- _mapPoints.push(_tempPoints[y]);
- }
- getRoutePointsAndWaypoints();
- }
- });
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.
2. For speed, you need to enter the "Average Speed (km/hr)" in the text box.
Code
- function CreateHTMTable(_latlng, _distance) {
- var _Speed = $( "#txtAvgSpeed" ).val();
- var _Time = parseInt(((_distance / 1000) / _Speed) * 60);;
- if (_htmlTrCount - 1 == 0) {
- _Time = 0;
- _distance = 0;
- }
- var html = '' ;
- var title = new Array( "A" , "B" , "C" , "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N" , "O" );
- html = html +"<tr id=\"" + _htmlTrCount + "\">" ;
- html = html +"<td style=\"width: 80px;\">" + _htmlTrCount + "</td>" ;
- html = html +"<td style=\"width: 80px;\"><span id=\"Title_" + _htmlTrCount + "\">" + title[_htmlTrCount - 1] + "</span></td>" ;
- html = html +"<td style=\"width: 100px;\"><span id=\"lat_" + _htmlTrCount + "\">" + parent.String(_latlng).split( "," )[0].substring(1, 8) + "</span></td>" ;
- html = html +"<td style=\"width: 100px;\"><span id=\"lng_" + _htmlTrCount + "\">" + parent.String(_latlng).split( "," )[1].substring(1, 8) + "</span></td>" ;
- html = html +"<td style=\"width: 100px;\"><span id=\"dir_" + _htmlTrCount + "\">" + _distance + "</span></td>" ;
- html = html +"<td style=\"width: 70px;\"><span id=\"time_" + _htmlTrCount + "\">" + _Time + "</span></td>" ;
- html = html +"<td style=\"width: 60px;\"><img alt=\"DeleteLocation\" src=\"Images/Delete.jpg\" onclick=\"return deleteLocation(" + _htmlTrCount + ");\" /></td>" ;
- html = html +"</tr>" ;
- $("#HtmlTable" ).append(html);
- draganddrophtmltablerows();
- }
The following code will help you to calculate distance and speed.
NOTE:
- 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.
- To better understand, download the source code in the attachment and run it to test it.
- I have used the Google map API v3 for this article.
- Please comment on this article for better improvement and I hope you enjoy the article.
Google Maps Drawing Distance Code
Source: https://www.c-sharpcorner.com/UploadFile/8911c4/how-to-draw-routes-and-calculate-route-time-and-distance-on/