Shalu
Shalu

Reputation: 61

Calculate Distance Between Two Postcodes In PHP

I'd like to calculate the distance between two postal codes in India. I've found the Google Map API and I'm trying to use it with this code:

$url =
"http://maps.googleapis.com/maps/api/distancematrix/json?origins=144216&
destinations=160017&mode=driving&language=en-EN&sensor=false";
   $data   = @file_get_contents($url);
   $result = json_decode($data, true); //print_r($result);  //outputs the array    $distances = array( // converts the units
   "meters" => $result["rows"][0]["elements"][0]["distance"]["value"],
   "kilometers" => $result["rows"][0]["elements"][0]["distance"]["value"] / 1000,
   "yards" => $result["rows"][0]["elements"][0]["distance"]["value"] * 1.0936133,
   "miles" => $result["rows"][0]["elements"][0]["distance"]["value"] * 0.000621371    );        
print_r($distances);

It is showing this output:

Array ( 
  [meters] => 5497949 
  [kilometers] => 5497.949 
  [yards] => 6012630.1491217 
  [miles] => 3416.266068079
)

The resulting distance is much bigger than it should be. The actual distance between these places is about 200 km.

What can I do to make this work correctly?

Upvotes: 1

Views: 6929

Answers (1)

Gerald Schneider
Gerald Schneider

Reputation: 17797

If you take a look at the result from google you will notice that it is calculating a route from india to russia.

"destination_addresses" : [ "Wologda, Oblast Wologda, Russland, 160017" ],
"origin_addresses" : [ "Punjab 144216, Indien" ],

This happens because you only provided postal codes, without reference from which country they are. I assume you want to calculate a route within india, since your profile shows that you are from there.

If you just add ,india to your postal codes, like this:

http://maps.googleapis.com/maps/api/distancematrix/json?origins=144216,india&destinations=160017,india&mode=driving&language=en-EN&sensor=false

You get a result that looks much more like what you want:

{
   "destination_addresses" : [ "Chandigarh, 160017, India" ],
   "origin_addresses" : [ "Punjab 144216, India" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "201 km",
                  "value" : 200693
               },
               "duration" : {
                  "text" : "3 hours 30 mins",
                  "value" : 12625
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Upvotes: 4

Related Questions