distance between 2 points google maps

In Php I am trying to find thw driving distance between 2 given points.
The 2 points can be given as addresses or lat/long as I have all this information.

This code given me the distamce without having to add a API key?

1) How do I add the address in and no the city for the driving distance?

2) How would I instead add the lat/long values for 2 points instead of the cities?
$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=Dover&mode=driving&language=en&sensor=false';
$data = file_get_contents($url);
$data = utf8_decode($data);
$obj = json_decode($data);

echo($obj->rows[0]->elements[0]->distance->text); //km
echo($obj->rows[0]->elements[0]->distance->value); // meters

Open in new window

jagguyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
This is a fairly complicated question because of the Google interaction, but it is simplified by using two lat/lng points.  You can compute the distance via plane geometry if these are close together and via the Haversine formula if these are further apart.  Where it gets difficult is in the "driving" distance.  You must use polyline computations (several integrated point-to-point coordinates) recomputing at every intersection where the driver turns.  Frankly, if I were Google, I would not make this information available free to the public (nobody else does) and I would require an API key.  It is valuable information and it's used by some multi-billion dollar companies to great competitive advantage (Uber).  So when you're looking for this without paying or adding an API key, you may be looking for something that is not readily available, or copyrighted, etc.

We have two articles here at E-E that cover some of the issues, and there may be more that I'm not aware of.  See if these can help you get started with your application.

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_4276-What-is-near-me-Proximity-calculations-using-PHP-and-MySQL.html

http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_9854-Using-GeoCodes-to-Find-an-Average-Location.html

This might be useful, too.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3350-Using-the-Google-Maps-API-in-PHP.html
0
Ray PaseurCommented:
This will get the text data.
http://iconoun.com/demo/temp_jagguy.php
<?php // demo/temp_jagguy.php
/**
 * http://www.experts-exchange.com/questions/28698780/distance-between-2-points-google-maps.html
 */
error_reporting(E_ALL);
echo '<pre>';


$url = 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=London&destinations=Dover&mode=driving&language=en&sensor=false';
$dat = file_get_contents($url);
$dat = utf8_decode($dat);
$obj = json_decode($dat);

// ACTIVATE THIS TO SEE THE ENTIRE OBJECT
// var_dump($obj);

// SHOW THE DISTANCE
var_dump($obj->rows[0]->elements[0]->distance->text);

/*
 * DATA LOOKS LIKE THIS
 *
object(stdClass)#1 (4) {
  ["destination_addresses"]=>
  array(1) {
    [0]=>
    string(15) "Dover, Kent, UK"
  }
  ["origin_addresses"]=>
  array(1) {
    [0]=>
    string(10) "London, UK"
  }
  ["rows"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (1) {
      ["elements"]=>
      array(1) {
        [0]=>
        object(stdClass)#3 (3) {
          ["distance"]=>
          object(stdClass)#4 (2) {
            ["text"]=>
            string(6) "139 km"
            ["value"]=>
            int(138792)
          }
          ["duration"]=>
          object(stdClass)#5 (2) {
            ["text"]=>
            string(14) "1 hour 48 mins"
            ["value"]=>
            int(6475)
          }
          ["status"]=>
          string(2) "OK"
        }
      }
    }
  }
  ["status"]=>
  string(2) "OK"
}
*/

Open in new window

To get the lat/lng values, you would need to geocode the city locations.  These may not be precise, but given that the distance is 139 km, an imprecision of a couple of km is not a big deal.
0
jagguyAuthor Commented:
Hi,

This should not be complicated as you just put in 2 points lat/long and get an answer.

Google maps API isnt working and thats why this is a problem.

I have the correct lat/log points as i check this on google maps but the driving distance is some 25% out.

Why doesnt google maps API work?

   foreach ($tutors  as $key => $item):
           $tutlat = $item['Tutor']['address_lat'];
           $tutlong = $item['Tutor']['address_long'];
        
            $testUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$stlat.",".$stlong."&destinations=".$tutlat.",".$tutlong."&mode=driving&language=en&sensor=false";

           $data1 = file_get_contents($testUrl);
           $data = utf8_decode($data1);
           $obj = json_decode($data1);
           $dist2=$obj->rows[0]->elements[0]->distance->text;

  

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

jagguyAuthor Commented:
Here is an example to explain what is happening.

Test data for lat/long (not people I know)
(point1)
Address Lat: -38.041968
Address Long: 145.26416599999993

(point 2)
 Address Lat: -37.988981
Address Long: 145.53447499999993

The distance between these 2 points on Google maps says 41.3km but on the Google api below for the same lat/long points I get 33.7km which is too inaccurate to rely on. What is going on with Google API as it doesnt seem to work?

  $stlat = $student['Student']['address_lat'];
  $stlong = $student['Student']['address_long'];
 foreach ($tutors  as $key => $item):
           $tutlat = $item['Tutor']['address_lat']; //this is the lat/long above
           $tutlong = $item['Tutor']['address_long'];
           $testUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$stlat.",".$stlong."&destinations=".$tutlat.",".$tutlong."&mode=driving&language=en&sensor=false";

           $data1 = file_get_contents($testUrl);
           $data = utf8_decode($data1);
           $obj = json_decode($data1);
          $dist2=$obj->rows[0]->elements[0]->distance->text;
          debug($obj->rows[0]->elements[0]->distance->text); //km




      endforeach;
0
Ray PaseurCommented:
I can't speak for Google, but one possibility might be that there is a discrepancy between "as the crow flies" distance and driving distance, which would have to include a route (maybe a good route, maybe a bad route) and turns around obstacles.  Here is some of what I've found.

This page might be worth reading:
https://developers.google.com/maps/documentation/geocoding/intro

This script...
<?php // demo/temp_jagguy.php
/**
 * http://www.experts-exchange.com/questions/28698780/distance-between-2-points-google-maps.html
 */
error_reporting(E_ALL);
echo '<pre>';

$stlat   = -38.041968;
$stlong  = 145.26416599999993;
$tutlat  = -37.988981;
$tutlong = 145.53447499999993;

$testUrl = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$stlat.",".$stlong."&destinations=".$tutlat.",".$tutlong."&mode=driving&language=en&sensor=false";
$data1   = file_get_contents($testUrl);
$obj     = json_decode($data1);

var_dump($obj);

Open in new window

Returns the following object:
object(stdClass)#1 (4) {
  ["destination_addresses"]=>
  array(1) {
    [0]=>
    string(53) "575 Gembrook Road, Pakenham Upper VIC 3810, Australia"
  }
  ["origin_addresses"]=>
  array(1) {
    [0]=>
    string(49) "9 Willand Court, Hampton Park VIC 3976, Australia"
  }
  ["rows"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (1) {
      ["elements"]=>
      array(1) {
        [0]=>
        object(stdClass)#3 (3) {
          ["distance"]=>
          object(stdClass)#4 (2) {
            ["text"]=>
            string(7) "33.7 km"
            ["value"]=>
            int(33749)
          }
          ["duration"]=>
          object(stdClass)#5 (2) {
            ["text"]=>
            string(7) "36 mins"
            ["value"]=>
            int(2135)
          }
          ["status"]=>
          string(2) "OK"
        }
      }
    }
  }
  ["status"]=>
  string(2) "OK"
}

Open in new window

A screen shot of the associated Google map is attached.
Google Map Driving Directions
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
Further to discrepancies in driving distance vs Haversine distance calculations, I found that driving distance was more accurate as the distances got longer.  At 100+ miles the driving distance was rarely more than 10% off the Haversine calculation.  But at very short distances, I found the same discrepancy you are seeing -- 25% was not uncommon.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.