How to calculate distance with javascript and Google Maps API

Reading time: About 5 minutes

This article focuses on straight line distance. If you’re looking for driving distance then read my newest tutorial: How to calculate driving distance with Google Maps API.

To make your location-sensitive web app truly valuable, you’ll need to be ready to answer these questions:

  • What are the closest _________ nearby?
  • How far away is _________?
  • What is the distance between _________ and _________?

Unfortunately, how to actually calculate distances has been somewhat elusive for many developers.

Until now.

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 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" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API Example: Extraction of Geocoding Data</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" class="address_input" size="40" />
        <input type="text" name="address2" value="Address 2" class="address_input" size="40" />
        <input type="submit" name="find" 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;

Next we’ll define our <body> onload event which prepares the Google Maps API for our requests.

1
2
3
function initialize() {
	geocoder = new GClientGeocoder();
}

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. Call calculateDistance()
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};
					calculateDistance();
				}
			});
		}
	});
}

Finally calculateDistance() calculates the distance based on the Great Circle Distance uses Google’s distanceFrom() method to calculate the distance in miles and kilometers between the two latitude and longitudes. Then it outputs the full addresses and distances to <p id="results">.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function calculateDistance()
{
	try
	{
		var glatlng1 = new GLatLng(location1.lat, location1.lon);
		var glatlng2 = new GLatLng(location2.lat, location2.lon);
		var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
		var kmdistance = (miledistance * 1.609344).toFixed(1);
 
		document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + '<br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
	}
	catch (error)
	{
		alert(error);
	}
}

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
36
37
38
39
40
41
42
43
44
45
46
var geocoder, location1, location2;
 
function initialize() {
	geocoder = new GClientGeocoder();
}
 
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};
					calculateDistance();
				}
			});
		}
	});
}
 
function calculateDistance()
{
	try
	{
		var glatlng1 = new GLatLng(location1.lat, location1.lon);
		var glatlng2 = new GLatLng(location2.lat, location2.lon);
		var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
		var kmdistance = (miledistance * 1.609344).toFixed(1);
 
		document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + '<br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
	}
	catch (error)
	{
		alert(error);
	}
}

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
63
64
65
66
67
68
69
70
71
72
73
<!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" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps JavaScript API Example: Extraction of Geocoding Data</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;
 
	function initialize() {
		geocoder = new GClientGeocoder();
	}
 
	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};
						calculateDistance();
					}
				});
			}
		});
	}
 
	function calculateDistance()
	{
		try
		{
			var glatlng1 = new GLatLng(location1.lat, location1.lon);
			var glatlng2 = new GLatLng(location2.lat, location2.lon);
			var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
			var kmdistance = (miledistance * 1.609344).toFixed(1);
 
			document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + '<br /><strong>Address 2: </strong>' + location2.address + '<br /><strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
		}
		catch (error)
		{
			alert(error);
		}
	}
 
    </script>
  </head>
 
  <body onload="initialize()">
 
    <form action="#" onsubmit="showLocation(); return false;">
      <p>
        <input type="text" name="address1" value="Address 1" class="address_input" size="40" />
        <input type="text" name="address2" value="Address 2" class="address_input" size="40" />
        <input type="submit" name="find" 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

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.

54 comments skip to comment form

  1. Chris Wright said— 46 minutes later

    Great article and a cracking idea…

    Not too sure about the accuracy of the maths though.
    I took two points in the UK (RG26 5BP & ME7 2DH) and it estimated a distance of 48miles.
    Now I know you state ‘circular’ distance, but even so, that appears to be rather short.

    Google
    Directions

    Is there not an API function to return the ‘distance’ between two points without the need for the extra maths calculation.

    In the example above, there is over a 50mile difference.
    Now you’ve stirred my interest, I will have to go read up on this later on.

    But still, you’ve highlighted how easy it is to provide this functionality and it’s a cracking idea.

    Cheers

    Chris

    #1
  2. Pamela Fox said— 11 hours later

    Hey there-

    Great article, but your final app violates the terms of use. According to the terms, the geocoder must be used in conjunction with a map. So your code should have a GMap2 in it as well.

    Thanks!

    #2
  3. cancel bubble said— 2 days later

    Having some math problems on this end. I should end up with roughly around 12 miles for the 2 test addresses I’m using, but the app is telling me:

    1.062803697052385 miles

    Also, seems like a toFixed(1) or (2) would be a nice addition.

    #3
  4. Brian Cray said— 1 week later

    Post and code updated!

    Now the distance calculation is really damn accurate! :) BIG thanks to everyone for pointing out the flaws!

    #4
  5. deb walton said— 1 week later

    i apologize for asking before thoroughly scouring thru your “How to calculate the distance between two addresses with javascript and Google Maps API”, (updated just today!) but i think this will calculate straight line distance and not actual driving distance, right? my client wants to start a local delivery service that charges a % per mile, so what i need is actual driving distances to plug into my online payment form.
    i got a tom tom recently, it senses my position, plots my route, and shows my actual driving distance and i was wanting to be able to find something i can plug into a form that will yield this milage value. since one end of the route is static, i need the form to calculate the milage using the address input fields. is there an app/javascript/etc that will do this?
    also, what do you charge for using your code in my projects?

    #5
  6. Brian Cray said— 1 week later

    Hi Deb,

    Yes this will calculate straight line distance, and not all the turns and diversions associated with roads. For that, you’ll need to turn to the Google MAPS API for driving directions and do some fancy stuff there (beyond the scope of this article).

    If you’d like to use this code, feel free to use it. While it may not be an ideal solution, it provides some kind of estimation, which is better than nothing.

    #6
  7. Ruhani Rabin said— 2 weeks later

    Brian,

    I was working on a office project which involve similar things.. for buses and rails etc. This will help me to screamingly shorten the development time.. thanks a lot.. and dugg.

    #7
  8. Pamela Fox said— 2 weeks later

    The current code is still against our Terms of Use, and is being passed around quite a bit. Please atleast put a warning in that developers shouldn’t use this code without also using a map on their site, or we’ll have multiple ToU-violating sites out there. You can contact me for more information about the Terms, if you’re confused.

    Thanks!

    #8
  9. Brian Cray said— 2 weeks later

    Pamela: Thank you for the notice and I apologize for the delay. The code and post have been updated with a terms of service warning.

    Readers: You must display a Google map when using the Google Maps API

    #9
  10. iPraj said— 2 weeks later

    cool..
    If you use GDirections, it’ll give you driving distance between two places.

    var gDir = new GDirections();
    gDir.observe(“load”,function(){
    //using prototype, u can use any other to attach event
    alert(gDir.getDistance().meters);
    //display results
    }
    //onSearch
    gDir.load(“from: place1 to: place2″);

    wassay ?

    #10
  11. Brian Cray said— 2 weeks later

    iPraj:

    Great idea! While the .observe method isn’t reliable right now, I tweaked your code to use the GEvent.addEventListener method and got the code working. Soon I will add your code to the article. Thanks so much for sharing your knowledge!

    #11
  12. iPraj said— 2 weeks later

    welx.
    If you reeally wanna make it rich, then you can use gDirectionsOptions http://tinyurl.com/2bfbm2 using which u can get driving path between those two places.
    You can show that path –
    here’s cool tutorial for that – http://tinyurl.com/dggkxk
    You, of course, will need to tweak it a lil bit…

    #12
  13. Brian Cray said— 2 weeks later

    iPraj:

    For the sake of this article, I wanted to keep it to calculating distance, because distance is relevant in more cases than driving directions. See my sample questions at the top of the article for the cases where only distance is necessary.

    Good start to your blog BTW iPraj

    #13
  14. iPraj said— 2 weeks later

    “I wanted to keep it to calculating distance, because distance is relevant in more cases than driving directions.”
    Ohh ok..
    I thought, when ppl ask for distance between two places, they mostly mean driving distance. coz direct distance may not be useful (or accurate) if you actually wanna go there..
    (well may be, it is, if you are flying.. :) )

    neways some thoughts/suggestions -
    * What are the closest _________ nearby?
    try google local api that will help a lot..

    * How far away is _________?
    check http://tinyurl.com/dauh7c ip to geolocation mapping.. this will make your tool even better coz it’ll find out where user currently is.. And then you can tell distance from that point to the one he’s asking about.

    * What is the distance between ___ and ___?
    umm.. dnt have any more info on this one :)

    regards

    #14
  15. Brian Cray said— 2 weeks later

    iPraj:

    All great points. I actually use IP to location geomapping. The Google AJAX API does it automatically :)

    #15
  16. iPraj said— 2 weeks later

    “I actually use IP to location geomapping. The Google AJAX API does it automatically”
    Oh.. this one was new for me.. Thanx man..

    #16
  17. jason said— 2 weeks later

    You warn about Google requiring a Google Map when using the API…

    but I noticed your demo is missing a map?

    #17
  18. Brian Cray said— 2 weeks later

    Jason: Yes, in your own applications you should show a map somewhere on your site

    #18
  19. henry said— 2 weeks later

    hi craig i am trying to use your code in some jsp code.But how ever its only return the distance of one address…?how could i modify it to calculate the distances from all the addresses my jsp page is bringing from the database

    #19
  20. henry said— 2 weeks later

    in addition to my firt post, i have read from other sites that you cannot call javascript from server side,but in this case where i need it to calculate the distances of all the addresses from the database in while loop,how could i over come this.I am using JSP/Java please help.Thank you for your time

    #20
  21. cancel bubble said— 2 weeks later

    Hi,

    Following up on my post above, my two test addresses are showing up as:

    Distance: 11 miles (or 18 kilometers)

    I’m pretty sure my car’s odometer recorded my two test addresses as 12.x miles, but hey, yours is pretty damn close!

    Also, are you rounding up/down?

    #21
  22. Brian Cray said— 2 weeks later

    rounding to the nearest decimal point.

    It should be noted that this calculates straight line distance. But I am going to update it soon to also calculate actual driving distance :)

    #22
  23. sae said— 2 weeks later

    Can anyone beat 12,411 miles apart? Sen Monorom, Cambodia to Pangoa, Peru…

    #23
  24. Brian Cray said— 2 weeks later

    Sae: Impressive :)

    #24
  25. Dumitru said— 3 weeks later

    Hm…why don’t you use the GApi functions to calculate the distance? http://code.google.com/apis/maps/documentation/reference.html#GLatLng.distanceFrom

    It returns the distance in meters then you just have to convert it. Here is an example where I used it:
    http://www.vtraceroute.com/

    #25
  26. Brian Cray said— 3 weeks later

    Updated to use Google’s distanceFrom() method instead of manual caluclations. Thanks to Pamela Fox and Dumitru for pointing out the method

    #26
  27. Alonzo said— 1 month later

    One day I hope to be half the genius that you are.
    Thanks for inspiring us that are trying to learn.

    I looked at your example at
    http://briancray.com/wp-content/uploads/2009/04/distance.html
    and I’m not sure if it has been updated to use distancefrom() method, because miles calculated differ from those on Googles driving directions.
    Is there somewhere I can see your most recent example that gives the more accurate mileage like what I might find using google maps? Thanks in advance

    #27
  28. RandyThePilot said— 1 month later

    Brian,
    This is very helpful stuff. I have been developing

    #28
  29. rtpHarry said— 1 month later

    Unrelated but didnt have time to look for a proper place to submit this.

    Your “Learn More” image at the footer of this post doesnt link anywhere.

    #29
  30. Kenny said— 1 month later

    Hello Brian, does your code now return driving distance yet? or it’s still return straight line distance? I’m working on an app that requires driving distance.

    Thank you very much for the tutorial.

    #30
  31. RK said— 2 months later

    Can you plz help me to find out actual distance? In my application I have to display actual distances from the searching locations to few nearest locations in descending order adjacent to the map.

    #31
  32. Andrew said— 2 months later

    May 24, 2009
    Hello Brian,

    Good work & great tutoring! Unfortunately I’m asking the same question as others: Does your code now return driving distance or is it still straight line distance?

    Couple things you could do to prevent this question being asked again (before you update it):
    1) Ask your commentors to date their comments. (That way we can compare the question date with your update date).
    2) Clarify in you header that it is “Straight Line” Distance or “Driving” Distance (or that both are coded).

    Keep up the good work!

    #32
  33. keerthi said— 2 months later

    hi Brian Cray

    do you know to get driving distance between to point. any function for google api .please help me. i am check ur code but there are diffrent with ur calculation and google. why is that?????

    #33
  34. Joshua said— 2 months later

    Very impressive work Brian ! Wondering, how I can calculate WALKING DISTANCE between two points ? any help pls.

    #34
  35. Felipe said— 2 months later

    Thanks Brian for sharing your knowledge, u rule!

    #35
  36. Leon Papazianis said— 3 months later

    Hi Brian

    REALY COOL tutorial man. Good job it helped me a lot getting around with google map api.
    I was just wondering could you please answer to me if your web app calculates the driving distance the straight line between the two postcodes. It would be really helpful if you could send me the final version of the code which calculates the driving distance cause I am really confused which one is the latest…

    Thanx a lot Brian

    Kindest regards,
    Leon

    #36
  37. rizwan said— 3 months later

    is there any way you can select the shortest route for distance calculation?

    #37
  38. kalyan said— 3 months later

    i need a google api where i can give a zip code and a distance.
    It will give all the zipcodes within that distance

    #38
  39. Brian Cray said— 5 months later

    If you want driving distance, go here: http://briancray.com/2009/06/23/calculate-driving-distance-google-maps-api/

    #39
  40. Kyle said— 5 months later

    Hey Brian,

    I am actually having difficulty doing this for multiple address’s.

    I am not very familiar with this API and have tried many different ways to have address 1 be compared to get distance with created address 2 / 3 / and 4.

    If you could be of any assistance I would greatly appreciate it. Thanks for the foundation if not!

    #40
  41. distance said— 6 months later

    I have used ones this http://distancestool.com <= good tool check the script of this tool.

    #41
  42. Nathan said— 6 months later

    Hi,

    Tried “hd21ua” in Address 1, “m320pg” in Address 2 and it brought up India for the second address. I then corrected the second Post Code as “M32 0PG” and it brought up 153 miles whereas the distance is in fact about 30-40 miles.

    Thanks

    #42
  43. Dev said— 6 months later

    Hello Brian,

    Its great for the single address. But I am having difficulties to apply for the multiple address’s.

    I want to to compare e.g. Address1=’75070′ with Address2=’99776,99777,99778,99779,99780,99781,99782,99783,99784,99785,99786,99788,99789,99790,99791,99801′. But it is not happening. I have tried with the JavaScript split method but failed.

    It will be great if I can get some assistance for this.

    #43
  44. Dev said— 6 months later

    Hello,
    How to apply for multiple location. Please help.

    #44
  45. Pandi Palanichamy said— 6 months later

    Very Nice to basic level programmers like me

    #45
  46. randyrr said— 6 months later

    Hey Guys, I can’t seem to get any info for Trinidad and Tobago? Can anyone provide more info?

    #46
  47. K. Crowley said— 8 months later

    Can you show me same the code with address one already inserted into the code and address two inserted by the user? zipcode_1 (59740), zipcode_2 (user inserts into form)

    #47
  48. Just Me said— 9 months later

    Hello

    I need a function that only returns the distance between 2 addresses
    I was look in to your code but I am running into some problems

    So I was hoping you could help me create a function in javascript:

    function(address1,address2){
    —-code—-
    return ‘distance in miles or km:’+distance
    }

    Anyone who can help?

    THX

    #48
  49. koko said— 9 months later

    Thanks for sharing~

    #49
  50. Ryan said— 9 months later

    Loved this!!! thanks so much for the above code – saved tons of my time

    thank you!

    #50
  51. Keith Nielsen said— 11 months later

    This code is great and is half what I am looking for.

    I was also after bearing eg 167 degrees etc. I’m not a programmer but I assume that this would be easy enough to do. Any ideas would be appeciated.

    Thanks,

    Keith

    #51
  52. Prashant said— on April 1, 2009 later

    Nice, It was easy way to calculate distance,
    Great work, but I think it is violating Google map terms and conditions,
    Is there any other way for same?

    #52
  53. Bhavin Mehta said— on April 1, 2009 later

    Awesome, one.
    This code helps me very much, that I have wind up all the points related to my distance calculation..

    Though, I need to use zip code worldwide to get all the information regarding to city, state, country, latitude, longitude etc.

    So, if more help provided, I will be thankful to U.

    Thanks,,

    Bhavin Mehta

    #53
  54. Jitendra Sherchan said— on April 1, 2009 later

    Very nice indeed…..but i have encountered strange javascript alert error
    while i enter address and then submit which says “TypeError: location2 is undefined”.however if i cancel alert then submit the form again i get the correct results…..I tested in your site it works very nicely but in mine its showing that error.
    Any help is highly appreciated….Thank you….

    #54
  55. Respond to this post—

Return to navigation
301