Calculate Distance Between Two Postcodes in php [closed]

廉价感情. 提交于 2019-12-25 19:46:43

问题


I'd like to calculate the distance between two postal codes in India. I've found the Google Map API and am 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?


回答1:


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"
}


来源:https://stackoverflow.com/questions/23261707/calculate-distance-between-two-postcodes-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!