How to calculate driving distance with Google Maps API

Reading time: About 6 minutes

Once upon a time I wrote How to calculate distance with javascript and Google Maps API. This article showed my readers how to calculate the straight line distance between two addresses. It turns out that people really wanted the driving distance between two addresses. I get an e-mail about this about once a day.

Today I will finally provide the long–awaited much–anticipated tutorial: how to calculate driving distance between two addresses using javascript and google maps API.

What I’ve built for you here is a javascript/Google Maps-driven web app that will take two fuzzy locations/addresses, turn them into full addresses and coordinates, and calculate the driving distance in miles and kilometers between them. So again, input two fuzzy address and output full addresses and distance. Sounds like a win for the you and your users.

Let’s step through the code to see how I did it. If you don’t want to learn about the code, go ahead and see the end result with source code.

The HTML

The HTML is pretty basic, but there are a few things to note:

  • Change the google maps API key to your own. Mine will not work on your domain. If you don’t have one, grab your Google Maps API key for free.
  • The form submits to a function named showLocation() and the body loads with a function named initialize(). We’ll build these in the next section.
  • The empty <p id="results"> element at the bottom of the HTML is used to output the results.
  • Advanced JS devs: This uses inline javascript events and javascript in the <head> for the sake of simplicity. If you know how to move javascript externally, that is a better way to go.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <meta name="robots" content="noindex,follow" />
    <title>Calculate driving distance with Google Maps API</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
    <!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
  </head>
 
  <body onload="initialize()">
 
    <form action="#" onsubmit="showLocation(); return false;">
      <p>
        <input type="text" name="address1" value="Address 1" />
        <input type="text" name="address2" value="Address 2" />
        <input type="submit" value="Search" />
      </p>
    </form>
    <p id="results"></p>
 
  </body>
</html>

Now let’s look at the javascript, where the real magic happens. We’ll look at the javascript in more detail than we did with the HTML.

Stepping through the Javascript

If you’d like skip the steps to the complete javascript code

First we’ll define global variables used in more than one function

1
var geocoder, location1, location2, gDir;

Next we’ll define our <body> onload event which prepares the Google Maps API for our requests and prepares to calculate the distance. Here’s the steps it goes through:

  1. Line 1 & 2: Assign Google’s geocoder (GClientGeocoder()) and Google’s directions API (GDirections()) to global variables
  2. Line 3: Add a “load” even listener to the directions API. Which means, when Google finishes calculating the driving distance, the following steps are performed:
    1. The driving distance is calculated from gDir.getDistance().meters in miles and kilometers
    2. The address and distance information is printed to the screen in to #results <div>
1
2
3
4
5
6
7
8
9
function initialize() {
	geocoder = new GClientGeocoder();
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", function() {
		var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
		var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
		document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
	});
}

Next we’ll define showLocation(), which is called when the user submits the form with the two fuzzy addresses. Here’s the steps it goes through:

  1. Attempt to get the first location’s information from the Google Maps API;
  2. Put the first location’s information including lat, lon, and full address into an object called location1;
  3. Attempt to get the second location’s information from the Google Maps API;
  4. Put the second location’s information including lat, lon, and full address into an object called location2;
  5. Use Google’s directions API as gDir to “load” the driving distance (which triggers the “load” event listener we defined above)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function showLocation() {
	geocoder.getLocations(document.forms[0].address1.value, function (response) {
		if (!response || response.Status.code != 200)
		{
			alert("Sorry, we were unable to geocode the first address");
		}
		else
		{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			geocoder.getLocations(document.forms[0].address2.value, function (response) {
				if (!response || response.Status.code != 200)
				{
					alert("Sorry, we were unable to geocode the second address");
				}
				else
				{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					gDir.load('from: ' + location1.address + ' to: ' + location2.address);
				}
			});
		}
	});
}

Completed Javascript

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
var geocoder, location1, location2, gDir;
 
function initialize() {
	geocoder = new GClientGeocoder();
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", function() {
		var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
		var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
		document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
	});
}
 
function showLocation() {
	geocoder.getLocations(document.forms[0].address1.value, function (response) {
		if (!response || response.Status.code != 200)
		{
			alert("Sorry, we were unable to geocode the first address");
		}
		else
		{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			geocoder.getLocations(document.forms[0].address2.value, function (response) {
				if (!response || response.Status.code != 200)
				{
					alert("Sorry, we were unable to geocode the second address");
				}
				else
				{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					gDir.load('from: ' + location1.address + ' to: ' + location2.address);
				}
			});
		}
	});
}

Advanced javascript developers: If you want to, feel free to put the above code into an external javascript file.

All of the source code together in one working file

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	<meta name="robots" content="noindex,follow" />
	<title>Calculate driving distance with Google Maps API</title>
	<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
	<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
	<script type="text/javascript">
 
	var geocoder, location1, location2, gDir;
 
	function initialize() {
		geocoder = new GClientGeocoder();
		gDir = new GDirections();
		GEvent.addListener(gDir, "load", function() {
			var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
			var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
			document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
		});
	}
 
	function showLocation() {
		geocoder.getLocations(document.forms[0].address1.value, function (response) {
			if (!response || response.Status.code != 200)
			{
				alert("Sorry, we were unable to geocode the first address");
			}
			else
			{
				location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
				geocoder.getLocations(document.forms[0].address2.value, function (response) {
					if (!response || response.Status.code != 200)
					{
						alert("Sorry, we were unable to geocode the second address");
					}
					else
					{
						location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
						gDir.load('from: ' + location1.address + ' to: ' + location2.address);
					}
				});
			}
		});
	}
 
	</script>
</head>
 
<body onload="initialize()">
 
	<form action="#" onsubmit="showLocation(); return false;">
		<p>
			<input type="text" name="address1" value="Address 1" />
			<input type="text" name="address2" value="Address 2" />
			<input type="submit" value="Search" />
		</p>
	</form>
	<p id="results"></p>
 
</body>
</html>

The end result

Your hard work has paid off! See the end result with source code

I’ve written quite a bit about geolocation and Google Maps API. If this is a topic that interests you, subscribe to my blog. If you use this, let me know how it works for you by leaving a response. Thank you!

Google Terms of Service Warning: According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API.

94 comments skip to comment form

  1. user said— 20 hours later

    How i can add Google map to this? Now it only shows distance but can i add map to visualize that distance?

    #1
  2. Brian Cray said— 23 hours later

    User: You may find this code example useful: http://code.google.com/apis/maps/documentation/examples/directions-simple.html

    #2
  3. Mick said— 2 days later

    Do you think you would be able to help me add an output that says how much a trip would cost. I would like 1 mile = $1, and then that would be added onto $25.
    I appreciate your help!

    #3
  4. Brian Cray said— 2 days later

    To calculate: After line 7 of the “Completed Javascript” you would have:
    var drivingDistanceMilesCost = drivingDistanceMiles + 25;

    To output: After line 9 of the “Completed Javascript” you would have:
    document.getElementById(‘results’).innerHTML = ‘$’ + drivingDistanceMilesCost;

    Cheers!

    #4
  5. jay said— 1 week later

    dear developer,

    thanks a lot for your source code. It is really help me to complete one of my project. god bless you my friend.

    #5
  6. jay said— 1 week later

    thanks brother

    #6
  7. Mohamed Jama said— 1 week later

    Excellent code, I was planning to use a php script that does the same thing but I prefer to do it on client side so this is perfect, will keep you updated when I finish the site.

    Thanks

    #7
  8. Myfacefriends said— 1 week later

    wonderful and amazing thanks!

    #8
  9. Brian Cray said— 1 week later

    Thanks everyone for your comments!

    Jay: You’re very welcome
    Mohamed: Glad this works well for you! Please let me know when you finish your project!
    Myfacefriends: Thanks :)

    #9
  10. Jeremy Akers said— 2 weeks later

    Awesome script Brian.

    Any ideas/insights on how one might integrate something like this with Google Spreadsheets? I have addresses in a column, and I’d like to populate a second column with the driving distance of that address from a static address. This way I can quickly compare the distances of many addresses from a single known point.

    #10
  11. Brian Cray said— 2 weeks later

    Thanks Jeremy. I don’t know enough about Google Spreadsheets to help you. and by “not enough” I mean I know nothing. :)

    #11
  12. phutrek said— 3 weeks later

    what if google maps api is suggesting 2 address for a single address? how do I choose any of the result?

    Example: try to put 275 Mammoth Rd, Manchester, NH, 03109 as one of the addresses and put any valid address on the 2nd address. If I click on ‘search’, you will get a error 602.

    How can i specify that one the choices given by google maps is the one i need.

    #12
  13. Vaibhav Kotalwar said— 3 weeks later

    Great!! well perticulatly I want to find Drving distance between 133 king street east , Toronto and 33 bloor st , Toronto this application showing right result as follows…
    Address 1: 133 King St E, Toronto, ON, Canada (43.6501921:-79.3730971)
    Address 2: 33 Bloor St W, Toronto, ON, Canada (43.6699666:-79.3882281)
    Driving Distance: 1.8541716376362045 miles (or 2.984 kilometers)

    My problem is that I have my code for finding direction between source and destination which is not locating above
    two addresses my code is as follows…

    Thanks in Advance.

    =====
    ShowDirections.jsp

    Coder Page

    var map = null;
    var geocoder = null;
    function load() {
    if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById(“map”));

    map.setCenter(new GLatLng(30.238034, -85.643955), 13);
    map.setMapType(G_NORMAL_MAP);
    map.enableDoubleClickZoom();
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();

    // ====== Restricting the range of Zoom Levels =====
    // Get the list of map types
    var mt = map.getMapTypes();

    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    for (var i=0; i<mt.length; i++) {
    mt[i].getMinimumResolution = function() {return 1;}
    mt[i].getMaximumResolution = function() {return 17;}
    }

    map.addControl(new GLargeMapControl());
    // map.addControl(new GMapTypeControl());

    geocoder = new GClientGeocoder();
    }
    getDirection(,)
    }

    function getDirection(fromAddress,toAddress)
    {

    document.getElementById(“panel”).innerText =” Retrieving maps from Google…….. “;

    var panel = document.getElementById(“panel”);
    //document.getElementById(“map”).innerHTML =”";
    var dir = new GDirections(map, panel);
    dir.load(fromAddress+” to “+toAddress);
    alert(dir.getStatus().code);

    if (document.getElementById(“panel”).innerText == ” Retrieving maps from Google…….. ” )
    {

    document.getElementById(“msg”).innerHTML =” Address is not locatable on google maps…..”;
    }
    }

    From: 
    To:   

    #13
  14. sameer said— 1 month later

    Dear Developer this is great .
    I need to calculate the driving distace between two lat long but i need it in Java,i have tested your page by entering the lat long points directly and it works fine. as for now i am calculating the distance using simple mathematical formula
    ###
    protected double distance(double pX, double pY) {
    double dx=this.x – pX;
    double dy=this.y – pY;
    double distance=Math.sqrt(dx * dx + dy * dy);
    return distance;
    }
    ###

    can you help me how to do this in java,

    Regards
    Sameer

    #14
  15. Brian Cray said— 1 month later

    phutrek: I’m really not sure on that one :(

    Vaibhav Kotalwar: It looks like when you call getDirection() you are not passing any addresses.

    sameer: Thanks for your comments. I’m not familiar enough with Java to help you. For a better equation though I’d check this: http://briancray.com/2009/04/01/how-to-calculate-the-distance-between-two-addresses-with-javascript-and-google-maps-api/

    #15
  16. sameer said— 1 month later

    Hello Brian

    Ya i looked into the code for calculating the straight line distance but i need the driving one.
    Is there a limit in google for number of times you ask for the driving distance in a day

    Regards
    Sameer

    #16
  17. Brian Cray said— 1 month later

    Sameer: If there is (and I believe there is) I don’t know it :)

    #17
  18. idev said— 1 month later

    Thanks for the script Brian….

    #18
  19. Busman said— 1 month later

    Hi Brian. Great Script. I’m trying to adapt it to calculate fares for a taxi website, first 20 miles @ 1.90 a mile, rest of miles @ 1.50 a mile.

    I’m struggling to even get the script to work :X

    #19
  20. Adrian said— 2 months later

    Brian, Thanks for the awesome code.

    Busman, I haven’t tested it, but this should work.
    After Line 7 type

    var Fare = (drivingDistanceMiles *1.5) + ((drivingDistanceMiles <20) ? (drivingDistanceMiles * 0.4) : 8);

    #20
  21. Busman said— 2 months later

    The script isn’t even functioning for me… I’m using firefox, latest version.

    I can’t get it to display anything for the UK :(

    #21
  22. Busman said— 2 months later

    I just got it to work, the problem is that it doesn’t work with UK postcodes or addresses.

    #22
  23. Noman said— 2 months later

    hi tahnx fr the toturial

    i create a programe which take the input location name and show its latitude and longitude according to google map…

    i want to calculate the distance b/w two cities on the basis of these latitude and longitude…

    i m using the farmula

    double getDistByHaversine(double lat1, double lon1, double lat2, double lon2, String unit)
    {
    double dLat =lat2 – lat1;
    double dLong = lon2 – lon1;

    double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLong/2) * Math.sin(dLong/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    return 6378.7*c;
    }

    but it not showing the correct result can u kindly help out me how i can do it with myself not using the google API…

    #23
  24. Adibi said— 2 months later

    Noman,

    I believe your formula is pretty accurate, specially for distances within te tropics. You’ll be a few miles off in distances between the tropics and the poles. But you’re calculating linear distance. Te distance on a straight line between the two points. What the google API is returning in this example is the driving distance, which will be bigger because there aren’t straight line roads (unless you live in Syberia I guess =)

    #24
  25. Mark said— 2 months later

    Vary interesting. I’m trying to get the same information (driving distance between two addresses) but for a large number of addresses in an Oracle Database. Since Google limits you to 15,000 records and wants to display the map, it doesn’t seem to be the right solution for me. Any suggestions? I can use Oracle, Java, Informatica or whatever, the trick is to deal with 4 million records with low costs. Thanks in advance.

    #25
  26. Adibi said— 2 months later

    Mark,

    A low cost solution could be to use Ms Streets and Trips or Map Point. You can find a two-year old version of the first on ebay for like $30.
    These products allow you to import and export data. Import all your addresses, and export including the distance from point X field in yout export profile. Then you can import that into your oracle DB.

    After you have done that for the 15K records, you can create a function using the Gmaps API descrived in this post to calculate distances for th records you create from now on.

    Hope it helps

    #26
  27. Noman said— 2 months later

    hi friends
    i create the code from which i get the distance b/w two point this is Areal distance not a traveling distance b/w two cities… i crerate my own logic to find distance only latitude and longitude are find using google service…
    run and Enjoy…
    if some One intresting to do anything else using google service than please let me know i am ready to work with him so please share your idea freely how we utilize google services…

    //////////////////////////////////////////////////////////// java code ///////////////////////////////////////////////////////////

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.StringTokenizer;

    public class test {
    String Latitude;
    String Longitude;

    /**
    * @param City
    */
    public void findLatLong(String City) {
    try {

    City = City.replaceAll(” “, “+”);

    // for finding lat and long /////////////////
    String url = “http://maps.google.com/maps/geo?q=”
    + City
    + “&+output=xml&oe=utf8\”"
    + “&sensor=false&key=ABQIAAAAVu6FLnwHDZ7nt0cmZfpnmRQVl2aZopxmRHQArsVnI0wW3Lv2qhQYvEEjT-yKshCHcutI9eBuDiqrIQ”;

    URL urlcon = new URL(url);
    HttpURLConnection uc = (HttpURLConnection) urlcon.openConnection();

    BufferedReader in = new BufferedReader(new InputStreamReader(uc
    .getInputStream()));
    String inputLine;

    StringBuffer bf = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
    bf.append(inputLine + “\n”);
    }
    in.close();

    StringTokenizer st = new StringTokenizer(bf.toString());
    while (st.hasMoreTokens()) {
    if (st.nextToken().startsWith(“\”coordinates\”")) {
    st.nextToken();
    this.setLongitude(st.nextToken().replaceAll(“,”, “”));
    this.setLatitude(st.nextToken().replaceAll(“,”, “”));

    break;
    }
    }
    } catch (Exception t) {
    t.printStackTrace();
    }
    }

    /**
    *
    * @return
    */
    public String getLatitude() {
    return Latitude;
    }

    /**
    *
    * @param latitude
    */
    public void setLatitude(String latitude) {
    Latitude = latitude;
    }

    /**
    *
    * @return
    */
    public String getLongitude() {
    return Longitude;
    }

    /**
    *
    * @param longitude
    */
    public void setLongitude(String longitude) {
    Longitude = longitude;
    }

    /******************************************************* */

    double getDistByHaversine(double lat1, double lon1, double lat2, double lon2, String unit)
    {
    double dLat =lat2 – lat1;// -2.20306276 = -1.10153138
    double dLong = lon2 – lon1;// 1.28540039

    double a =Math.sin(this.deg2rad(dLat/2)) * Math.sin(this.deg2rad(dLat/2)) + Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) * Math.sin(this.deg2rad(dLong/2)) * Math.sin(this.deg2rad(dLong/2));// -0.01922417 * -0.01922417 + 0.83214027 * 0.85284337 * 0.01121700 * 0.01121700 = 0.00036957 + 0.00008929 = 0.00045886
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));// = 2 * atan2(0.02142102,0.99977054) = 2 * 0.021422658624589 = 0.04284532

    return 6378.7*c; //= 273.29742514 kms from ibd to lhr
    }

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*:: This function converts decimal degrees to radians :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
    }

    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    /*:: This function converts radians to decimal degrees :*/
    /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
    private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
    }

    /**
    * @param a
    */
    /**
    * @param a
    */
    public static void main(String a[])
    {
    String city1=”new york”,city2=”paris”;

    test ob = new test();
    ob.findLatLong(city1);

    System.out.println(city1.toUpperCase()+” Lati: ” + ob.getLatitude() + ” Long: ”
    + ob.getLongitude());

    test ob2 = new test();
    ob2.findLatLong(city2);

    System.out.println(city2.toUpperCase()+” Lati: ” + ob2.getLatitude() + ” Long: ”
    + ob2.getLongitude());

    System.out.println(ob2.getDistByHaversine(Double.parseDouble(ob.getLatitude()), Double.parseDouble(ob.getLongitude()), Double.parseDouble(ob2.getLatitude()), Double.parseDouble(ob2.getLongitude()), “K”) + ” km\n”);

    }
    }

    /////////////////////////////////////////////////// End of code /////////////////////////////////////////////////////

    #27
  28. sameer said— 2 months later

    @ Noman

    in the same manner can you give two addresses or two latlong points so that it returns the driving distance between them ( google get Directions)
    coz you are accessing the URL and entering the location(address)
    which returns the latitude and longitude which are used to find the distance between two latlong points which is a straight line distance using Haversine Formula.
    I am having the latitude and longitude in my databse i need the driving distance between them….
    I am a beginner in programming

    #28
  29. Brian Cray said— 2 months later

    Sameer – if you’d like to calculate the distance between two lat/lon

    var glatlng1 = new GLatLng(location1.lat, location1.lon);
    var glatlng2 = new GLatLng(location2.lat, location2.lon);
    var miledistance2 = gDir.load('from: ' + location1.address + ' to: ' + location2.address);
    var miledistance3 = glatlng1.distanceFrom(glatlng2, 3959);
    var R = 3959; // earth's mean radius in miles
    var dLat = (location2.lat - location1.lat) * Math.PI / 180;
    var dLon = (location2.lon - location1.lon) * Math.PI / 180;
    var lat1 = location1.lat * Math.PI / 180;
    var lat2 = location2.lat * Math.PI / 180;
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c;
    var miledistance = d.toFixed(1);
    var kmdistance = (miledistance * 1.609344).toFixed(1);
    #29
  30. sameer said— 2 months later

    @ Brian

    ya but i need the real driving distance between two latlong points
    and i need it in Java.

    right now i am using your script to calculate the real driving distance ;-)

    the problem is that i need it in java to find the real driving distance

    Thank You Brian
    Regards
    Sameer

    #30
  31. Ingo said— 2 months later

    Dear Brian,
    your tutorial is very interesting. I got a question, how can I calculate multiple distances from lots of origins and destinations? And is there a way to put the results of the distances between the lat and long coordinates in an excel file?
    Thank you and best regards,
    Ingo

    #31
  32. Ingo said— 2 months later

    I´m looking for road distances.
    Thanks in any case!
    Brgds,
    Ingo

    #32
  33. Noman said— 2 months later

    @sameer
    hmmm okzz there is some real trick which i done with my browser i open the post request when using the google map so i get that url to find lat/long but keep in mind dear these distance are areal distance i don’t think so there is any farmula which can give me the road distance…

    little bit trick i trying these days to find the http url of google road map to finding the driving loc.. if i got so we easily extract the info which google response back to us on the when we send two point in requet….

    if someone have any idea how we get the result of driving distance using only http based request than share it with us…

    #33
  34. Josh said— 2 months later

    I was wondering if anyone could help me with displaying a map with the route on top of the code to display mileage. All i need is the map with the outlined path to be below the mileage output.

    #34
  35. Nommi said— 3 months later

    hello
    i create little applkication in which i calculate Areal distance and taking the driving direction from google without using there API this is pure java application and need internet connectivity to show result……..
    plzzz download the jar file from http://rs42.rapidshare.com/files/286355024/myDirection.jar hope u know how to run jar file…

    any comment and input is warmly welcome…

    #35
  36. Raj said— 3 months later

    MyDirection jar doesn’t work fine

    #36
  37. Raj said— 3 months later

    How can i calculate for Malaysia(map). MyDirection works only for India (map)
    Could you pls…. tell me how to customize in the code?

    #37
  38. Jarred Suisman said— 3 months later

    Thanks for posting this code Brian.

    @Raj and @Busman(older comment)

    Brian’s code takes the addresses you type in and tells Google to geocode them into latitude and longitude points.

    To use addresses from different countries, Google relies on which of their domains receives the request. In Brian’s HTML code(Top code box), line 7 you see:

    <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAA…etc

    Any request that is sent to the domain "maps.google.com" will try to geocode it as a United States address. Just like if you used "maps.google.it" it would try to geocode an Italian address into lat/long.

    @Raj: for Malaysian addresses on line 7 you would replace "maps.google.com" with "maps.google.com.my"

    @Busman: (if you still check this site): For UK addresses you would replace it with "maps.google.co.uk"

    Good Luck

    #38
  39. SV said— 3 months later

    I have a basic question. In fact i’m a little embarrassed to even ask this. I want the input box to be at least 425px wide… when i change the max chars it does nothing… if i put in width=”425 px” you see the change in dreamweaver but when I upload it online the box is the same size… i am using the code in this tutorial. Any suggestions?

    #39
  40. Brian Cray said— 3 months later

    you should do <input type=”text” style=”width:425px”>

    #40
  41. Raj said— 3 months later

    Thanks for your prompt reply. @Jarred Suisman

    I am trying to use Nommi’s “MyDirection” jar from rapid share. Using that application, i can find driving distance only in india. I would like to use it for Malaysian map maker.

    please tell me should i need to depend on anything else.

    #41
  42. SV said— 3 months later

    Brian,

    Thank you for your help! I can’t believe how fast you were able to respond. I can’t tell you how much I appriciate it! This was a really cool tutorial. It really helps.

    #42
  43. Raj said— 3 months later

    @Nommi

    Hi, you are parsing
    “http://www.google.com.my/mapmaker?hl=en&ctype=0&saddr=”
    to find out the driving distance.

    Could you pleas help in parsing
    “http://maps.google.com/maps?saddr=ipoh&daddr=taiping”
    to find out the driving distance.

    #43
  44. Roland said— 3 months later

    I am trying to modify this html to run through a high number of address pairs and find the driving distance between each pair of addresses. I have been unsuccessful at calling the showlocation() function from within a loop. To start, I just used a simple “for” loop counting from one to five, and appends the resulting distances into a variable (separated by a . One would expect the distance to be returned five times, however, this just returns the distance one time. If it is triggered by the click of the submit button, it loads the variable properly (appends as many values as times clicked). I am somewhat new to javascript. Any suggestions?

    #44
  45. Kim said— 4 months later

    Dear Sir,

    Thank you very much for your Tutorial.
    I am very interesting how to get the distance variable to calculate the price of the route. Ex. 100km x 1€ . I want to implement this variable in to a php site, so people can see how many they should pay for the route.
    Thank you in Advance.

    ps. sorry for my poor English

    #45
  46. Roland said— 4 months later

    For reference, here’s the javascript code i’m having problems with:
    Note, the first button calls load() directly, the second button calls a loop that is supposed to call load five times. It only calls it once. Thanks again for any help! It is not making sense why it is not working.

    Miles to … using Maps API

    //<![CDATA[
    google.load("maps", "2");
    var gdir;
    var miles = 0;
    var start = "seattle";
    var end = "portland";

    function load() {
    if (GBrowserIsCompatible()) {
    gdir = new google.maps.Directions();
    google.maps.Event.addListener(gdir, "load", handleLoad);
    gdir.load("from: "+start+" to: "+end, {getSteps: true});
    }
    }
    function handleLoad() {
    miles = miles + "” +gdir.getDistance().html
    document.getElementById(“totalMiles”).innerHTML = miles;
    }

    function loop(){
    var i=0;
    for (i=0;i

    Miles to …

    #46
  47. Ravi said— 4 months later

    Hi brian
    Great work

    can we implement autocomplete feature for the text fields?

    regards

    ravi

    #47
  48. Sid said— 4 months later

    Using this tutorial, how can you add a map that will visually show what you entered in the search boxes? I saw the link you posted with the example but it already has a route in the map. How can I impliment both examples to work like mapquest works?

    #48
  49. Pablo said— 4 months later

    I’m developing an app with PHP & MySQL, would you be ineterested to develop some code for me? if so I could show you what I need and you could give me a quote, ok? waiting to hear from you very soon, sincerely.

    Regards,

    Pablo

    #49
  50. Phil Gill Purple Chilli Design said— 4 months later

    Brian, I was actually going to develop this myself, looked for GUIDANCE, and ended up with your SOLUTION. You just saved me bags of time, and your code actually works. Hats off :)

    #50
  51. Stefan said— 4 months later

    First of all, great article Brian! I’ve been using something similar for a client of mine for a couple of months already. He’s getting lots of compliments and questions about this system. That made me think.

    I’d like to have a PHP version, just like Pablo, for my webapp. So, if there is anyone who can make this or knows where to find it. Please let me know :)
    It’s an application for taxi companies, so it has to be this exact version with driving distance, just not Client Side.

    #51
  52. malick mbaye said— 4 months later

    Good job man thanks a lot!!!!

    #52
  53. Zena said— 4 months later

    Hi, I am having problems using this. When I type in SW6 4NE (which is New Kings Road, London) it comes up with Germany! Any ideas on how to solve this? Thanks. Zena

    #53
  54. Punit Naker said— 4 months later

    I am using this code to calculate the cost per mile for a transport company. We want it to return the number of miles (which is does) and the user chooses via radio buttons whether they want a small van or a large van.

    If it is a small van its the Number of Miles x £0.95
    If it is a large van its the Number of Miles x £1.20

    As soon as i put in a if statement, it doesnt work!

    Any ideas?

    #54
  55. aaaDesigns said— 4 months later

    Hello All

    First of all a BIG THANKS to Brian for a wonderful script.

    I also have used it for a taxi website.

    Following on from a few PHP related questions above.

    Has anyone figured out how to convert either

    “var Fare”

    or “var drivingDistanceMilesCost” into a ‘php variable’ that can then be reused, or passed into an sql database?

    #55
  56. Gary said— 4 months later

    Brian – excellent tutorial !

    Like several other people here, I am also looking for a way to feed in multiple source lon & lats and multiple destination lon & lats, and have the distances provided for each permutation of source and destination.

    Similar to Roland, I cannot get this code to loop.

    Has anyone managed this successfully?

    Thanks in advance.

    #56
  57. ben said— 5 months later

    This is a great tutorial.. Thanks a lot, Brian!
    I desperately needed the functionality as a PHP class so I took a day off to code it for myself..
    It works for me now.
    If anyone is interested contact me via my website

    #57
  58. Luca said— 5 months later

    Hi Brian,

    thanks for your excellent tutorial. I came here because I am currently using a PHP version (no Javascript) and I am trying to understand if there is any fast and “legal” way to loop multiple addresses.

    I’ve got a Mysql database with a table of geo-locations. It’s very simple:

    LOCATION NAME (text)
    LATITUDE (number)
    LONGITUDE (number)

    That’s all. What I need to do is evaluate the distance of each location (350 so far) from a fixed destination (for example “National Park of Something, lat number, long number).

    What I do now is running a loop (350 times) that evaluates the distance for every location. I go on googlemaps website, get the distance, go back on my server and save the number on a “distances” table (one time query, distance is saved forever so I wont query googlemaps every time).

    That works fine, it takes 0.21 sec per query more or less. What I need to know is… does Google provides any sort of API/whatever that can cycle a list of coordinates on a specific destination, instead of doing that work from my server and querying the googlemaps website 350 times?

    Any idea/suggestion?

    #58
  59. JOhn said— 5 months later

    Hello! Im new here.. I’m so happy that i seen and visited your blog to get an idea how to calculate distance in straight line using google map and it works. My Problem now is, there’s one input in my site where the user can type there location and after clicking the submit button, i want to calculate the distance between one to many locations. not just between two locations. like for example,
    myLocation to 1st destination
    myLocation to 2nd destination
    myLocation to 3rd destination
    myLocation to 4th destination…
    please help me how to solve this problem….

    #59
  60. bill said— 6 months later

    Luca,

    I am interested in doing something similar to what you are doing. Can you provide more details about the method you are using now?

    Thanks,

    Bill

    #60
  61. Jessica Izaguirre said— 6 months later

    Thank you so much for this script, it works perfectly for my project :)

    #61
  62. J3 said— 6 months later

    This is the perfect script for me.. Thank you & a marry christmas

    #62
  63. Brian Cray said— 6 months later

    Happy Holidays! Enjoy your present =)

    #63
  64. Horla said— 6 months later

    Hi Brian,
    Thanks for this great work. I’m using it for my final year project. My request is: using this tutorial, how can I add a map that will visually show the two location entered in the search boxes?

    I’ve try to make it work and show the map (like on google map page) but it’s not working. kindly assist me in this regard as I need to display the map too. it’s for my final year project in college.

    #64
  65. Björn said— 6 months later

    Hi Brian,

    Can you please tell me if its possible and if so how to get the time it takes to drive the entered distance, can i replace .meters with .time?

    #65
  66. Bill said— 6 months later

    Thats amazing,its exaclty that i was finding !!!
    MANY THANKS !!!

    #66
  67. David said— 6 months later

    Hi, How do you shorten the results distance to like 9.6 in stead of 9.624418396564066?

    #67
  68. Jarred said— 6 months later

    @David
    Change this line:
    var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;

    To:
    var drivingDistanceMiles = (gDir.getDistance().meters / 1609.344).toFixed(1);//for 1 decimal place

    #68
  69. David said— 6 months later

    Great! Thanks Jarred:-)

    #69
  70. Chris said— 7 months later

    Great code, many thanks. I have one problem though. I’m calculating the driving distance for several pairs and for one of the locations I’m not getting any directions into or out of it. When I plug it into normal maps it returns directions but there are too many pairs to do this by hand. I tried finding a solution online and found this gmaps example: http://gmaps-samples.googlecode.com/svn/trunk/gdirections/directions-static.html but when I plug my locations into this I get the following error: “This route has too many vertices.” Does anyone know what this means or how I can adapt the code to remove the error?

    #70
  71. James said— 7 months later

    Thanks Brian exactly what I was looking for,
    Im pretty useless at coding so this guide saved me alot of time.

    Still trying to figure out how to show the map with the route plotted out as when I try, it causes the whole thing to stop working. Anyone got any ideas how to do this?

    http://edgwarelocalcars.co.uk/Booking.html

    #71
  72. Steve said— 7 months later

    Thanks Brian
    Great example. Have you thought of a way to find the latitude / longitude for a point along the path which is, say 100 miles along the path.
    So for example:
    Address 1: 10 Victoria St, West Rockhampton QLD 4700, Australia (-23.381403:150.486481)
    Address 2: 28 Queen St, Brisbane QLD 4000, Australia (-27.4711478:153.0232475)
    Driving Distance: 384.9394535910284 miles (or 619.5 kilometers)

    Finding the position along the route which is 100 miles from the start?

    #72
  73. Daniel said— 7 months later

    James (comment 71). I got this to work with a map being displayed as well. What you need to do is take the map code lines from inside it’s function initialize tag and include them inside the function initialize tag provided Brian’s distance calc code. I had two function initialize tags and since I don’t know squat about javascript, I didn’t realize that was a problem until I experimented. Hope that works.

    For anyone else who reads this, I combined this distance calculation with a map that displayed a marker on 1 address with the ui. The distance calc form appears just underneath the map on the page. I also hid the 2nd address field and entered a default address so that the user enters only their home address to calculate the distance to our company address.

    #73
  74. strangesoul said— 9 months later

    PLZ Can anyone help me to calculate fare of ::::

    $2.50 First 1/8 MILE…OR PART THEREOF
    .25 EACH ADDITIONAL 1/8 Mile
    $25.00 PER HOUR WAITING TIME
    EACH ADDITIONAL PASSENGER $2.00
    7% GA. STATE SALES TAX INCLUDED
    $15.00 Minimum

    #74
  75. Karel said— 9 months later

    Thanks Brian. This script was a great starting point.

    #75
  76. dominique said— 9 months later

    i want to let people insert the adresses at one page and then they go to the next page and there the result shows up. is that possible?

    #76
  77. warxsg said— 10 months later

    Hi all,

    I am pretty interested in calculating the dricing distance between two points.
    I’d like to integrate this function in an application of mine.
    Is it possible to get the same result using Google WebServices ?
    My application is running on .Net.
    Any suggestion ?
    Cheers.

    #77
  78. Rafiq said— 11 months later

    Thanks! Its Very useful article

    #78
  79. Will said— 11 months later

    Is there any way to do address by address? rather than postcode? So its more accurate?

    #79
  80. sivamyneni said— 11 months later

    how to loop the code? i got distance only for the last record. similar to Roland’s problem but i am calling the script form server side

    #80
  81. kumar said— 11 months later

    can u give the idea how to write the code in finding route map and finding the distance in google map and it has show on the map.

    #81
  82. Ryan said— 11 months later

    You could always just use a simple HTTP request with query strings! Google Maps returns a lovely KML document that is really easy to parse for a set of route directions and travel time/distance.

    #82
  83. Hiral Vyas said— 11 months later

    Hi,

    I used this script and working fine at my end.
    I need to display google map also accroding to entered address when user “Search”.

    Thanks

    #83
  84. Prajeevan said— 11 months later

    i’m actually wanting to use this in a iphone web app using iwebkit…. basically after a search result … it will list the stores according to the store’s location from the iphone…

    what i basically need to know is…. how can i get around this Terms about showing the map…. because its a tiny screen… can i simply give credit to google with their logo?

    #84
  85. Mark said— on June 23, 2009 later

    Hey Brian!
    In the first comment user said that he would like to include google maps to this distance application and than you posted a link http://code.google.com/apis/maps/documentation/examples/directions-simple.html but the link doesn’t work anymore. Can you please help me so i will be able to see a result?!

    Thank you in advance

    #85
  86. Praveen Aithal H said— on June 23, 2009 later

    Hi Brian!
    Amazing work.

    @Noman : I was stuck from long time. you made my day..

    Thank you both

    #86
  87. Noman said— on June 23, 2009 later

    @Praveen Aithal u welcome…
    well there is my post with my Nik name @Nommi in which i post my application link try it out and find the driving direction of whole world just entering your start and ending points … if download link expire than let me ur email i will send u my desktop application cheerzzzzz

    #87
  88. Praveen Aithal H said— on June 23, 2009 later

    @Noman: kind of you.

    I am stuck with one more prob Noman..
    Is there a way (in JAVA) to find out, whether a given point lies inside a polygon or not !!

    Thanks in advance

    #88
  89. Noman said— on June 23, 2009 later

    @Praveen Aithal:
    hmmm interesting but sorry i not done anything related to that.. it might be possible you can find such a info by using Google API or may be try to search such a info by using yahoo APi… i am not sure if Google map provide such a info if they providing in their Google map than also let me know..

    #89
  90. Jerome Gaynor said— on June 23, 2009 later

    This is great — but I need to do the same thing in PHP. How would I convert your code to use on the server-side?

    #90
  91. Michelle said— on June 23, 2009 later

    Hi Brian. This is great. However, I need to get the driving distance for a huge number of pairs of addresses, which I have stored in an Excel sheet. Do you have any ideas about how I could link those addresses to your web query and then output the distance to my excel file? I’ve tried everything and can’t seem to find another way to do this. Note — I am not at all fluent at web coding, which is definitely slowing things down. Any advice would be much appreciated!

    #91
  92. ali said— on June 23, 2009 later

    Very nice. Thank you for this.

    #92
  93. Uldis said— on June 23, 2009 later

    Tnx bro, your post is usefull for my project.

    #93
  94. Uldis said— on June 23, 2009 later

    Ok, if someone need not only distance, but map too – than you need add to JS 1 output line —

    document.getElementById(‘results3′).innerHTML = ”;

    and 1 html output line –

    #94
  95. Respond to this post—

Return to navigation
793