Now lets have a look on code. In this example I have created four text fields to get the Latitude and Longitude of from location and To location.
I have used the online java script library of google map api library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <html> <head> <title>Getting The Distance Between Two Locations Using Google MAP API</title> <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script> </head> <body> <div> <strong>From Location</strong><br/> <span>Latitude : </span> <input type="text" id="fromLat"/> <span>Longitude : </span> <input type="text" id="fromLng"/> <br/><br/> <strong>To Location</strong><br/> <span>Latitude : </span> <input type="text" id="toLat"/> <span>Longitude : </span> <input type="text" id="toLng"/> <br/><br/> <input type="button" value="Calculate Distance" onclick="getDistance()"/> <br/><br/> <strong>Distance : </strong> <span id="distance">0.00</span> <span> meters</span> </div> <script type="text/javascript"> function getDistance() { var fromLocation = new google.maps.LatLng($("#fromLat").val(), $("#fromLng").val()); var toLocation = new google.maps.LatLng($("#toLat").val(), $("#toLng").val()); var distance = google.maps.geometry.spherical.computeDistanceBetween(fromLocation, toLocation).toFixed(2); $("#distance").html(distance); } </script> </body> </html> |
Just copy the code and create a html file and open in the browser. Enter the Latitude and Longitude of From and To locations and click the 'Calculate Distance' button.
If you want you can improve the code by sending the Latitude and Longitude of From and To locations by using a method and get the distance.
Check My Other Articles About Google Maps.
1. Creating A Google Map Using Google Map API v3
2. Show Current Location In A Google Map Using Google Map API v3
3. Getting The Address Of Selected Location In Google Map Using Google Map API v3
4. Getting The Selected Latitude And Longitude From Google Map Using Google Map API v3
5. Google Map With Multiple Markers & Info Windows Using Google Map API v3
6. Getting The Direction Between Two Markers In Google Map Using Google MAP API
7. Getting The Direction Between Two Locations Using Google MAP API
8. Getting The Distance Between Two Markers In Google Map Using Google MAP API
9. Getting The Distance Between Two Locations Using Google MAP API
10. Getting The Nearest Places For A Location In Google Map Using Google MAP API
11. Google Map With InfoBubble
12. Google Maps Creating Polygon And Retrieving Coordinates