Question

Using Google Maps API to determine the driving distance between two locations

Asked by: Ray_Paseur

Building on this question:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_23531323.html

Visit this page and you will see that Google says the driving distance is 237 miles
http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=20016&daddr=15222&sll=39.693615,-78.54249&sspn=1.608247,3.633728&ie=UTF8&z=9

If you use the code snippet, Google says the driving distance is 245 miles.  You will need a Google API key to test it out.  Link here: http://code.google.com/apis/maps/signup.html

Those two answers are pretty close, and in fact, either answer is OK.  The central issue is getting the answer in a way that is programatically useful.

I want to know how to get step-wise driving distances from Google in a way that can be parsed in a PHP script.  If there is an HTTP solution that calls Google and returns a CSV or an XML string that would be ideal.  If you can show me the PHP code to "scrape" the answer out of the script below, that would be OK, too.

Thanks for your help,
Ray

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link href="/style.css" rel="stylesheet" type="text/css" />
<title>Miles to ... using Maps API</title>
<script type="text/javascript" src="http://www.google.com/jsapi?key=[your Google API Key]"></script>
<script type="text/javascript">
//<![CDATA[
google.load("maps", "2");
var gdir;
function load() {
        if (GBrowserIsCompatible()) {
                gdir = new google.maps.Directions();
                google.maps.Event.addListener(gdir, "load", handleLoad);
                gdir.load("from: Washington, DC to: Pittsburgh, PA", {getSteps: true});
        }
}
function handleLoad() {
        document.getElementById("totalMiles").innerHTML = gdir.getDistance().html;
}
window.onload = load;
window.onunload = google.maps.Unload;
//]]>
</script>
</head>
 
<body>
<h3>Miles to ... </h3>
 
<div id="totalMiles"></div>
 
</body>
</html>

                                  
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:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2008-07-08 at 17:31:23ID23548760
Tags

Google Maps API

,

XHTML

,

XML

Topics

Extensible Markup Language (XML)

,

JavaScript

,

PHP Scripting Language

Participating Experts
4
Points
500
Comments
17

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Distance between 2 addresses calculator
    I need to implement a 'miles from' calculator for distances between 2 addresses (not zipcodes as I'm dealing with very short distances - 1-10 miles mostly). Do I need to buy a service from someone or....? I'm working in PHP and MYSQL BTW.
  2. Post code distance calculation (php and mysql)
    Hello folks. I have a postcode database: Structure is: postcode x y The formula to calculate the (approximate) distance in miles, a straight line is apparently: sqrt(pow(($a_x-$b_x), 2) + pow(($a_y-$b_y),2))*0.0006; What I'd like to do is when someone enters their post...
  3. Using Google Maps API to determine the driving distance bet…
    I would like to determine the driving distance between two locations. I have a vague sense that I might be able to do this with Google Maps API. I have used zipcode-based geolocation algorithms and determined that the distance between Washington, DC and Pittsburgh, PA is ab...
  4. searching jobs within 30 miles ,40 miles
    Hi, i am working on job search functionality.here there is a option for the user to search the job within range of 10 miles, 20 miles, 300 miles etc like almost all job site provides for job search.But i am litttle confused about it to do .Bcz i am taking location and state...
  5. Miles to Kilometers
    Hello, at this example they are using Miles: http://econym.org.uk/gmap/example_cartrip.htm I like to use kilometers, I made some changes but they arn't correct. any 1 willing to help?

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: fiboPosted on 2008-07-08 at 23:24:27ID: 21960989

Searching in the main discussion group at http://groups.google.com/group/Google-Maps-API/ , it seems there is no "pure php" solution.
see for example the thread
http://groups.google.com/group/Google-Maps-API/browse_thread/thread/ed6ca03dd601c663/bce0a9c7fa3fa0d2

So the solution seems to first get a javascript page (eg, php-generated), run it to get back driving directions (asyncrhonously), then pack everything into an array (eg, XML or JSON type) which is then handed back to another php script.

See also
http://code.google.com/support/bin/answer.py?answer=66848

 

by: b0lsc0ttPosted on 2008-07-09 at 20:15:56ID: 21970205

Is this just to be used in a PHP script?  Will the server have the to and from addresses then?  Those won't come from input at all?

What is the xml or json needed for?  If it is just the miles then what else would go in the xml or json?  It seems like you just have one piece of info. :)

Getting this clarified will help to know the best solution.  Although Google doesn't have an official way to get the info we still may need to be able to do it just from PHP.  However if you are getting the addresses from the client then an AJAX method or form submission could be used to get the miles to your PHP script.  The API would be used but then a form or AJAX script would send it to the server.

Let me know if you have a question about this.

bol

 

by: Ray_PaseurPosted on 2008-07-10 at 05:33:53ID: 21972606

@bol: I know this is not a simple question.  Thanks for trying to help.

I don't have a problem getting the address from the clients; that is simple <form> input.  I don't have a problem geocoding the address (turns the address into a latitude/longitude pair).  You can call the Google geocoder or the Yahoo geocoder and get the latitude/longitude pairs.  The terms of service for either lets you geocode thousands of addresses each day, and that's plenty for my needs.

For example, if you want to get the geocoded address for zip code 20016, you can use the script in the code snippet.  Google returns a string of comma-separated values.  There is also a way to get back XML, but for geocoding, the CSV is simple to use.  You can also buy pre-coded data.  It comes from the US Census and other sources.

It's easy to compute the distance between two geocoded addresses, but the computation only gives the distance "as the crow flies."

So far, so good.

Now if I knew the turn-by-turn driving directions, and I geocoded each turn, I could incrementally compute the driving distance by adding together all the little distances between each turn.  This would be much closer to the odometer mileage.  It wouldn't account for wiggly roads, but that's OK.  This _may_ be how Google determines the driving distance.

But I don't really need that level of detail, I just need the total driving distance - in one, easy to access, number.  

If you go to this URL:
http://maps.google.com/maps?f=d&hl=en&geocode=&saddr=20016&daddr=15222&ie=UTF8&z=9&pw=2

You can see that Google computes the travel distance to be 237 miles.

What I am looking for is a way to extract that value -- 237 miles -- in a way that does not violate the terms of service.  I have looked at the source information on that page and I can write a script to parse the HTML.  But that's clearly not the "best" answer.

What I am looking for is a formal interface to Google, Yahoo or some other map service that can give me a CSV string or XML string that contains the overall driving distance information.

Does that clarify what I'm trying to find?

Thanks, Ray

$zip = '20016';
$url = "http://maps.google.com/maps/geo?q=" . $zip . "&output=csv&key=[your API key]";
 
if ($fp = fopen($url, 'r')) {
	$buf	= '';
	while (!feof($fp)) {
		$buf .= fgets($fp);
	}
	fclose($fp);
} else { die("Google maps/geo failed for $zip"); }
 
echo $zip . ': ' . $buf . "\n";
$x = explode(',', $buf);
var_dump($x);
 
// $x contains this:
// $x[0] = 200 if successful
// $x[1] = 5, an indicator of precision in the geolocation process
// $x[2] = latitude
// $x[3] = longitude
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

Select allOpen in new window

 

by: b0lsc0ttPosted on 2008-07-10 at 11:45:20ID: 21976290

Ray,

Yes that info helps and cleared things up. I am familiar with the geocoding option but don't see that it is needed for what you are trying to do here.  Now I think I know why you mentioned JSON but with just one value we should not need it and the API doesn't send it as JSON like the geocoding process does.

I am sorry if it seems like this will be a bit of a run around, especially after the first question on this, but if you are getting the to and from address from input then it is best to just use the API, have Javascript get the info, and then pass it to the server. We already have the first 2 done in the script I provided. The key for the last is will the page be submitted or refreshed (i.e. a form sent) or do you want the info to go to the server without reloading the page (i.e. using AJAX)?

I will be happy to provide details on either method and help you put it in your page. It would help to know what your form looks like if you need help with that part. If you also want to make sure the value doesn't have html or can't use meters then let me know. Removing the html or converting meters to miles is not hard.

Thanks again for that info. Hopefully this last little bit will do it.

bol

 

by: Ray_PaseurPosted on 2008-07-10 at 12:04:57ID: 21976441

bol, thanks.  In the code snippet is a sample of code that will isolate the driving distance.  I run that code on my server and it prints the answer.  It seems pretty reliable.  There are some local functions, but I'm sure you can figure them out if you read over the code.

It gives me back this output:
From 20016 to 15222 is 237 mi  about 4 hours 5 mins

What I'm looking for is a formal, Google-supported interface that will give me back the same information as I get in the $answer variable.

In the alternative, it could be an interface to Yahoo or any other mapping service.

That's really all I need.  

Best, Ray

// GET THE ZIP CODES (MAYBE FROM FORM INPUT)
$zip_home	= '20016'; 
$zip_away	= '15222'
 
// GET THE PRINTABLE DRIVING DIRECTIONS PAGE FROM GOOGLE
$google_url	= "http://maps.google.com/maps?f=d&hl=en&saddr=" . $zip_home . "&daddr=" . $zip_away . "&ie=UTF8&z=9&pw=2";
$google_html	= my_curl($google_url);
 
// TRUNCATE HEAD OF GOOGLE HTML STRING UP TO THE TIME AND DISTANCE TAG
$pointer	= strpos($google_html, "timedist ul");
if ($pointer === FALSE) { die("No timedist ul"); }
$google_html	= substr($google_html, $pointer, strlen($google_html));
 
// TRUNCATE TAIL OF GOOGLE HTML
$pointer	= strpos($google_html, "</td>");
$google_html	= substr($google_html, 0, $pointer);
 
// TIDY UP IN CASE GOOGLE EVER GOES TO STRICT
$google_html	= str_replace('"', '', $google_html);
 
// ISOLATE THE STRING WE WANT
$x = explode('<div class=pw>', $google_html);
$answer = trim(strip_tags($x[1]));
$answer	= str_replace('&#160;', ' ', $answer);
 
echo "From $zip_home to $zip_away is $answer \n";
                                              
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:

Select allOpen in new window

 

by: b0lsc0ttPosted on 2008-07-10 at 15:01:47ID: 21977765

Ray,

So are you not going to use form input then to get zips or the to and from addresses?  From what you have said and even the little comment in the code above it seems like you will.  If that is the case then great.  Forget what you have been asking regarding a server only solution.

I don't know of any of the free map or service sites that offer this for strictly server script use.  For various reasons they have all built it around an API design which depends on Javascript.  The option to scrape a page is prohibited or questionably allowed on the different sites I have seen that would provide this.  If the production version of this will be using a form then it is more difficult and seems to be a waste of your time to ignore the APIs and a Javascript inclusive solution.

If you really have to do this in just PHP then you could look at a paid option like the one at http://falconsolution.com/driving-distance-calculator/ .  You wouldn't have to worry about issues of scraping a page (i.e. legal issues or generated HTML issues) and it would work just in your PHP code (from the info they provide on their site).  For the specific zips you provided the results seemed a little off (when I tested on their site) but there may be some reason for that.  They might also not be as accurate as you want.

I know it seems like I am stuck on this.  If you are frustrated then I am too but I am trying to provide what you want and need and getting some conflicting info.  Of course maybe I am just dense and misreading something but that really doesn't seem to be the case.

The key is those sites that provide this free want you to do it with an API and Javascript.  There are PHP only options but they will cost money, be questionably legal (see note 1 below), or be much more complex to implement.  MS Live does have some developer tools that use SOAP and will work with .NET, PHP, etc but a quick read of the SDK seems to show the distance results returned by these would be like those you started with; the "circle" method and not really on roads and driving.

Let me know if you have a question about any of this.  I am definitely not trying to be difficult (quite the opposite) but seem stuck here.  Let me know what you think about this.  You won't hurt my feelings if you tell me to move on to another question because I believe I am repeating myself and I really dislike that. :)

bol

Note 1 - Google, MapQuest and Yahoo have clear prohibitions, MSN's maps is questionable or ambigious.  I looked at a few other sites but they were all like these, no easy PHP option and most prohibit scraping.

                                              
1:

Select allOpen in new window

 

by: Ray_PaseurPosted on 2008-07-10 at 15:45:03ID: 31474563

Thanks, Experts. I think the answer has to be a custom application.  No point in spending any more EE time on this one.  Best to all, ~Ray

 

by: Ray_PaseurPosted on 2008-07-10 at 15:45:55ID: 21978021

Time to put this thing out of its misery.  Best, ~Ray

 

by: fiboPosted on 2008-07-10 at 15:59:11ID: 21978101

B-)) Interesting project and discussion! Thx for the points.

 

by: b0lsc0ttPosted on 2008-07-10 at 18:07:17ID: 21979131

Your welcome!  I am glad I could help a bit.  Hopefully it wasn't painful.  ;)  It definitely has been interesting.

Thanks for the fun question, the grade and the points.

bol

 

by: intangiblemediaPosted on 2008-12-05 at 05:25:15ID: 23104549

Hi Ray,

Did you manage to do that in the end? Did you resolve the problem?
My question is similar:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_23954105.html

-------------

What im trying to do is, if i know:
1) Point A (in Lat Long)
2) Point B (in Lat Long)

I want to:
1) Calculate the distance using roads in KM
2) Offer driving directions
3)  Display the average time to get location by car / walking
4)  Use the GOOGLE Static Maps API to create the graphic using the markers to delineate the path that the Google Maps API has used to create the route. (so retrieve the lat long of the waypoints so i can use them in google static maps api)

All of this needs to be done on the server in PHP and presented as variables for output in HTML - i can run the php variables in the page but not javascript so everything must be processed server side.

 

by: Ray_PaseurPosted on 2008-12-05 at 06:29:13ID: 23104998

Hi, I understand the question, believe me.  I have not solved the issue of driving distance, but I haven't got it as a business problem any more - I just decided the effort was going to yield only marginal improvement for my particular app, and I did not want to run afoul of the Google TOS, so I shelved it.  Your issue appears to be different and it may be a more central part of your app.

Since I posted that query last July, Google Maps has added many new features.  Such a thing may have come available since then.  But I haven't looked lately.

In any case, Good Luck! ~Ray

 

by: intangiblemediaPosted on 2008-12-05 at 06:36:44ID: 23105050

I think for me its a question of offering the most accurate advice for the end user - I know i can do the "as the crow flies" calculation and present it as --aprox but i would rather be realistic. Also, i need to be able to get those damn waypoints to create the static image using the Google Maps Static API.

Care to enlighten me on those Google TOS? Is it wise building the app using their mapping service?
All i know is that they limit it to 15K requests a day, which i wont be hitting (but maybe later)

thanks Ray

 

by: Ray_PaseurPosted on 2008-12-05 at 06:45:13ID: 23105126

Sorry, I'm not really qualified to offer advice on the Google TOS - I just made evaluations for my own case.  You should consult a lawyer with IP experience for a qualified opinion.

In my case, I use both the Google geocoder and the Google maps service together.  So far the results have been fine.  I depend on Javascript in the browser.  And I make the assumption that the driving distance will be proportional to the "crow flies" distance.   So if I find that two points are close together geographically, I simply accept the "risk" that there is a river between them, with no bridge.  Since I am presenting a Google map, the client has to deal with the final choice of proximity and route.

FWIW, the XML from the Yahoo geocoder is somewhat simpler than the XML from the Google geocoder.

 

by: intangiblemediaPosted on 2008-12-05 at 07:19:49ID: 23105447

mmm... thanks for that... given me worry about the implication for the project though as im building something for mobiles.... So you cant display a map with javascript because of the limitation of mobiles, hence using the Google Static Maps API. But to get distances etc, i need to use the Google Maps API (somehow, maybe through AJAX) and then plot everything on a static map....

Thanks for the tips and i will keep ploughing the forums!

 

by: Ray_PaseurPosted on 2008-12-05 at 07:21:37ID: 23105460

Yep, the Forum's the place to look.  Maybe look at Chrome support?  Anyway, good luck with the project. ~Ray

 

by: cyberal_Posted on 2009-02-12 at 00:13:31ID: 23620115

Hey guys,

I don't know if you are still interested in this, but here's a suggestion.

Make an HTTP request, retrieve XML (actually it's KML) with the directions step by step. Take a look at the response and see if it's good enough for your needs.

Here's a sample URL:

http://maps.google.com/maps?f=d&source=s_d&saddr=539+Taylor+Court,+Mountain+View,+CA+94043&daddr=Las Vegas,+NV&hl=en&geocode=&mra=ls&output=kml&jsv=145d&sll=37.395426,-122.065959&sspn=0.010024,0.04549&g=67+E+Evelyn+Ave+%23+8,+Mountain+View,+CA+94041

Key parameters here are:
saddr => Start address (Human-readable or GPS x,y format)
daddr => End address (same as before)
output => "kml"

optionally:
doflg => "ptk" for retrieving the distance in km or "ptm" for miles. Default depends on the locale for the address.

PS: If you don't need a step-by-step direction and all you need is total distance and time, I'd suggest using "output=dragdir". This will return a shorter JSON object with an attribute containing that precise info.

Also, check out this link for more gmaps parameters: http://mapki.com/wiki/Google_Map_Parameters

Cheers

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...