Link to home
Start Free TrialLog in
Avatar of jagguy
jagguyFlag for Australia

asked on

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

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

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.

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

https://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.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3350-Using-the-Google-Maps-API-in-PHP.html
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.
Avatar of jagguy

ASKER

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

Avatar of jagguy

ASKER

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;
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.