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.
Here I have chosen Mumbai as the starting location.
- You can choose the second location by double-clicking on another location on the map or drag the "B" icon to the second location.
Here I have chosen Pune as my second location. - You can choose another location by double-clicking on the map.
Here I have chosen Hyderabad as my third location. - 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
- //You can calculate directions (using a variety of methods of transportation) by using the DirectionsService object.
- var directionsService = new google.maps.DirectionsService();
- //Define a variable with all map points.
- var _mapPoints = new Array();
- //Define a DirectionsRenderer variable.
- var _directionsRenderer = '';
- //InitializeMap() function is used to initialize google map on page load.
- function InitializeMap() {
- //DirectionsRenderer() is a used to render the direction
- _directionsRenderer = new google.maps.DirectionsRenderer();
- //Set the your own options for map.
- var myOptions = {
- zoom: 6,
- center: new google.maps.LatLng(21.7679, 78.8718),
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- //Define the map.
- var map = new google.maps.Map(document.getElementById("dvMap"), myOptions);
- //Set the map for directionsRenderer
- _directionsRenderer.setMap(map);
- //Set different options for DirectionsRenderer mehtods.
- //draggable option will used to drag the route.
- _directionsRenderer.setOptions({
- draggable: true
- });
- //Add the doubel click event to map.
- google.maps.event.addListener(map, "dblclick", function (event) {
- //Check if Avg Speed value is enter.
- if ($("#txtAvgSpeed").val() == '') {
- alert("Please enter the Average Speed (km/hr).");
- $("#txtAvgSpeed").focus();
- return false;
- }
- var _currentPoints = event.latLng;
- _mapPoints.push(_currentPoints);
- getRoutePointsAndWaypoints();
- });
- //Add an event to route direction. This will fire when the direction is changed.
- google.maps.event.addListener(_directionsRenderer, 'directions_changed', function () {
- computeTotalDistanceforRoute(_directionsRenderer.directions);
- });
- }
2. Get the route points and waypoints
- //getRoutePointsAndWaypoints() will help you to pass points and waypoints to drawRoute() function
- function getRoutePointsAndWaypoints() {
- //Define a variable for waypoints.
- var _waypoints = new Array();
- if (_mapPoints.length > 2) //Waypoints will be come.
- {
- for (var j = 1; j < _mapPoints.length - 1; j++) {
- var address = _mapPoints[j];
- if (address !== "") {
- _waypoints.push({
- location: address,
- stopover: true //stopover is used to show marker on map for waypoints
- });
- }
- }
- //Call a drawRoute() function
- drawRoute(_mapPoints[0], _mapPoints[_mapPoints.length - 1], _waypoints);
- } else if (_mapPoints.length > 1) {
- //Call a drawRoute() function only for start and end locations
- drawRoute(_mapPoints[_mapPoints.length - 2], _mapPoints[_mapPoints.length - 1], _waypoints);
- } else {
- //Call a drawRoute() function only for one point as start and end locations.
- drawRoute(_mapPoints[_mapPoints.length - 1], _mapPoints[_mapPoints.length - 1], _waypoints);
- }
- }
3. Draw the route
The following function is used to draw the route.
- //drawRoute() will help actual draw the route on map.
- function drawRoute(originAddress, destinationAddress, _waypoints) {
- //Define a request variable for route .
- var _request = '';
- //This is for more then two locatins
- if (_waypoints.length > 0) {
- _request = {
- origin: originAddress,
- destination: destinationAddress,
- waypoints: _waypoints, //an array of waypoints
- optimizeWaypoints: true, //set to true if you want google to determine the shortest route or false to use the order specified.
- travelMode: google.maps.DirectionsTravelMode.DRIVING
- };
- } else {
- //This is for one or two locations. Here noway point is used.
- _request = {
- origin: originAddress,
- destination: destinationAddress,
- travelMode: google.maps.DirectionsTravelMode.DRIVING
- };
- }
- //This will take the request and draw the route and return response and status as output
- 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:
- //This will useful to delete the 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:



- //This will useful to swap rows the location
- function draganddrophtmltablerows() {
- var _tempPoints = new Array();
- // Initialise the first table (as before)
- $("#HtmlTable").tableDnD();
- // Initialise the second table specifying a dragClass and an onDrop function that will display an alert
- $("#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
The following code will help you to calculate distance and speed.

- //CreateHTMTable() will help you to create a dynamic html table
- 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();
- }
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.

ibs demoPosted Jul 13, 2020, 5:50 PM
It looks like a complete solution for how to use google map API.. when i run the default.apx with my api key the app launches fine but when i try to click to set a starting point it just zooms in.. it is suppose to add a row in the html table but nothing shows up.
Dinesh GabhanePosted Nov 12, 2019, 5:59 AM
Nice Article. Thanks
Suhel KikaPosted Dec 19, 2017, 3:45 AM
Hii map is not displayed..i think google api key i have to define...but where i should define..please tell me
sndg ranjithPosted Dec 14, 2017, 4:42 AM
!!!Thanks for your code.i want to edit this routes..i have stored lattitude and longtitude in database and retrieved from database but for this map need to edit .kindly help me any possible way
Pawan BugaliaPosted Nov 12, 2017, 1:59 AM
Hello MaheshThanks for your code.It is very useful. But I have one issue. Hope you can help. Issue: - I changed the default.aspx to default.php and run it in XAMP(localhost). It was working fine in local. Then I upload it to my server then it ask for API key. I give API key in code. Now Map is displaying but plotting point A and B is not working. Can you help me to resolve this.
jayant daphalePosted Jul 19, 2017, 3:15 AM
I am double click on map but point is not show there plz help me
Vikas VermaPosted Mar 8, 2017, 1:17 AM
Great article bro :) and i also find a good way to draw route on google map using pure html we can use iframe for this read more about this here : http://growwebsite.com/2016/12/04/how-to-draw-route-on-google-map-using-pure-html/
Vanka ManikanthPosted Feb 14, 2017, 3:48 AM
Fine, actually i need code that having start,waypoint and destination text boxes with the autocomplete places and onclick of submit button i want the view on map by showing given values in the text boxes.Do mail at [email protected] https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints i want this to be implemented with autocomplete placeholders of start,waypoint and destination.Hope you understood bro..NOTE:DO NOT USE ASP.NET, only javascript would be better.I actually done but the code does not show waypoints in the map.If at all you require the code i will send you,just modify and revert back.Do comment your mail id.Regards
Erick LopezPosted Jan 11, 2017, 5:22 PM
Hello, could you help me? With an initial location, final location and waypoints I draw a route and I show the directions to follow (step by step), when I change the route by dragging a point on the map the directions change, how can I save those indications To show them later. I already have the initial, final location and the waypoints, I only need to save the modifications in the route.
Gingerbox01 MobilityPosted Oct 8, 2016, 1:09 AM
Thx u it's very useful code
Kenndher AranaPosted Sep 16, 2016, 1:18 PM
I have no idea how to run the code in map.zip to try .. please help me? Thank you.
Kenndher AranaPosted Sep 16, 2016, 1:06 PM
Hello, could you help me? Download the Map.Zip esta But apparently empty , when I try to open the Visual Studio project from the three folders are empty without hay solution files ?
kalu singh raoPosted Jul 7, 2016, 1:44 AM
Nice...
Ankit SinghPosted Jun 24, 2016, 5:12 AM
hi can you help in getting location(Formatted Address using Reverse geocoding) . I tried reversegeocode while creating table but didn't worked out for me
Humayun Kabir MamunPosted Jun 12, 2016, 5:13 AM
Nice...
Thiruppathi RPosted Jun 3, 2016, 11:25 AM
Great share...
Nicko VisionPosted Mar 21, 2016, 11:19 AM
Hi, How can i add a mark in a certain point in the path. For example, I make a path between Pune and Mumbai, the user can enter a value (Miles driven) and i want to show where they will be at that point, if he drove 20 miles he will be in a point inside the path, if he drove 40 he will be closer to mumbai. Thanks
vanita nikamPosted Nov 18, 2015, 1:27 AM
Nice solution ,but i want to load the lat long from my database and show name of location on map in asp.net ,Please help me
chamath madushanPosted Jun 17, 2015, 4:03 AM
sir, plz help me to save the loaded table data into mysql database
karen ordonezPosted Apr 12, 2015, 9:25 PM
do you know if we can calculate the distance to a point that it's different to the route?
Jheel DoshiPosted Feb 26, 2015, 10:24 PM
We are running it in visual studio professional 2013 and we are running default.cs.aspx and default.aspx . Can you tell us if we are doing anything wrong.
Jheel DoshiPosted Feb 26, 2015, 7:17 AM
I have downloaded the entire code but cant seem to run it as im getting an empty form and no map or text boxes. Can you please help me with this
AbdulPosted Jan 13, 2015, 5:26 AM
nice one... But i need one thing if i give source and destination it will shows automatically via route, that means only main area locality along that route... can u help me..
darsa dasPosted Nov 19, 2014, 12:48 AM
can i provide static map points in the code if yes where is place it can you provide the example.
Romina ShimaPosted Aug 4, 2014, 11:39 AM
Hi Mahesh,Nice article! Can u pls help understand how to add direction arrows in the routes?
SaranyaPosted Jul 1, 2014, 5:57 AM
diz code shows the google map but im not getting the route.
Sony P rajuPosted Jun 6, 2014, 4:15 AM
diz code shows the google map and route but diz wilnot show the text box
Sony P rajuPosted Jun 6, 2014, 4:14 AM
send me the full code in javascript..plz its urgent
Sony P rajuPosted Jun 6, 2014, 4:11 AM
plz snd me the full code in jquery
Sony P rajuPosted Jun 6, 2014, 3:24 AM
plz snd me the full code
Sony P rajuPosted Jun 6, 2014, 1:57 AM
i have copied and pasted this code into my computer but it wil not show any text boxes.It only show the map.Plz help me
azhar nawazPosted May 16, 2014, 3:50 AM
function codeLatLng(latlong1) { alert(latlong1); latlong1 = latlong1.replace('(',''); latlong1 = latlong1.replace(')',''); alert(latlong1); var input = latlong1; var latlngStr = input.split(',', 2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng2= new google.maps.LatLng(lat, lng); geocoder.geocode({ 'latLng': latlng2 }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { alert(results[1].formatted_address); } else { alert('No results found'); } } else { alert('Geocoder failed due to: ' status); } }); }
azhar nawazPosted May 16, 2014, 3:50 AM
create this function
Bikash PanigrahiPosted May 12, 2014, 3:07 AM
Hi Mahesh Please let me know how to get the address in the html table?
Shri Ram SinghPosted Mar 28, 2014, 4:20 AM
Dear, mahesh please send me new code of javascript for searching destination by the help of dropdownlist plz help me.. becz i don't able to make this type of code so please kindly send me new code for google map on [email protected].
Mahesh AllePosted Mar 27, 2014, 7:50 AM
Hi, You need to use reverse geocoding concept. After selecting the location form drop down list, you can pass the lat and long to my JavaScript code (i.e. double click function) form c# code. Here lat and logn will be your drop down-list selected value. Hope you got this.
Shri Ram SinghPosted Mar 27, 2014, 6:27 AM
Dear, Mahesh i want to select two or more than two city on google map by usnig dropdownlist for finding distance and time. i don't want to select city using double click on google map. plz help me.
hari babuPosted Mar 25, 2014, 5:23 AM
i mean that drawing paths in map to store in database
hari babuPosted Mar 25, 2014, 5:22 AM
how to store data in databse
Mahesh AllePosted Jan 31, 2014, 12:31 AM
This article will not cover alternate routes. Also I dot have any idea about alternate routes.
RaviPosted Jan 31, 2014, 12:03 AM
Dear Mahesh, How to get alternate routes with provideroute alternatives.....Also i want to apply radio buttons to alternate routes.
Mahesh AllePosted Jan 26, 2014, 11:44 PM
Dear Masood, There is no server side code on this. This will completely written with JavaScript, Jquery and Google map api3.
masood farooqPosted Jan 24, 2014, 12:36 PM
How to convert this code in php? by the way is this code using any server side? i think all of these tasks or performing on client side and there is no role of server. am i right?
Mahesh AllePosted Jan 16, 2014, 3:47 AM
Dear Ashih, Google map required JavaScript API. For that you have use the JavaScript. With out Java Script it is not possible,
Ashish ThakurPosted Jan 16, 2014, 2:00 AM
I want use same code in vb.net application.. please help me.. there does not use javascript.
Mahesh AllePosted Jan 6, 2014, 5:03 AM
Dear gkrishna rao, I dot have any idea about maps in windows applications.
G Krishna RaoPosted Jan 6, 2014, 4:00 AM
hy Mahesh,, its a very good post., but same thing I want to implement using windows application(c#)could u please refer something to it...?
Mahesh AllePosted Dec 8, 2013, 11:44 PM
Dear Prakash, you need to open "Map.zip" file in .rar or .zip software. This application is designed in asp.net and not in J2EE. So you cannot open "Map.zip" in eclipse.
prakashPosted Dec 6, 2013, 12:32 PM
I was not able to open "Map.zip"in eclipse j2ee can you help me...
Mahesh AllePosted Nov 13, 2013, 3:50 AM
Dear prakash, You can download the source code "Map.zip" from top of this article. In that source code you will find the java script code.
prakashPosted Nov 13, 2013, 3:17 AM
Can you provide java script code for this will be useful ..
Mahesh AllePosted Oct 30, 2013, 3:30 AM
Dear Ravi, you can see this link https://developers.google.com/maps/documentation/javascript/examples/places-searchbox It will give you some idea.
ravihanok bingiPosted Oct 30, 2013, 3:10 AM
Hi Mahesh, Thanks for giving beautiful API. how to search locations with text boxes instead double click.
Mahesh AllePosted Oct 1, 2013, 2:31 AM
Dear Bhavavan, In CreateHTMTable() function, you need to write var _distanceInKm = parseInt(_distance / 1000); This will give you distance in KM.
bhagavan rajuPosted Oct 1, 2013, 1:08 AM
Dear Ravi Kumar I have to set distance in Km . May I know where to set
bhagavan rajuPosted Sep 30, 2013, 2:32 PM
Intresting.Nice article . You saved my time alot Thanks man
Mahesh AllePosted Sep 24, 2013, 5:34 AM
Dear Ravi Kumar, I have seen the link which you provide. But on this link they are try to draw only straight line. But I am try to dray a route and not line. I thing you got my point.
Ravi KumarPosted Sep 24, 2013, 5:17 AM
hi nice article .. I have also found another example to draw interactive polyline path from source to destination in Google Maps v3 visit http://www.etechpulse.com/2013/09/draw-interactive-polyline-path-from.html Thanks!
amjad islam amjadPosted Jun 22, 2013, 8:11 AM
good job main