Google Distance Matrix API error Invalid Request

主宰稳场 提交于 2019-12-12 06:26:17

问题


I have the following code to create a request in PHP to get a response from Google Distance Matrix API:

//get info from google
$map_url = 'https://maps.googleapis.com/maps/api/distancematrix/json';
$midnight = strtotime('tomorrow midnight');
$params = array(
    'units' => 'metric',
    'origins' => str_replace(' ', '+', str_replace('.', '', $arr['address'])),
    'destinations' => str_replace(' ', '+', str_replace('.', '', $rink_arr['address'])),
    'traffic_model' => 'best_guess',
    'departure_time' => $midnight + $rink_arr['avg_time'],
    'key' => 'API_KEY'
);

//get data
$url = $map_url.'?'.http_build_query($params);
$json = file_get_contents($url);    
echo '<pre>';
echo $url.'<br><br>';
print_r($json);
echo '</pre>';
exit();

When I run this code I get the following response:

https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=2141+Southview+Ave%2C+Innisfil%2C+ON+L9S+1H4&destinations=190+Bayview+Dr%2C+Barrie%2C+ON+L5N+9B4&traffic_model=best_guess&departure_time=1479523235&key=API_KEY

{
   "destination_addresses" : [],
   "origin_addresses" : [],
   "rows" : [],
   "status" : "INVALID_REQUEST"
}

But here's the catch when I copy the url from the above response and paste it in a browser it works. I get the following response:

{
   "destination_addresses" : [ "190 Bayview Dr, Barrie, ON L4N 2Z4, Canada" ],
   "origin_addresses" : [ "2141 Southview Ave, Innisfil, ON L9S 1H4, Canada" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "9.0 km",
                  "value" : 9027
               },
               "duration" : {
                  "text" : "13 mins",
                  "value" : 758
               },
               "duration_in_traffic" : {
                   "text" : "12 mins",
                   "value" : 720
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

Has anyone had a similar problem and know why this is the case? I have tried changing the URL but it doesn't make sense that it works in a browser and not in file_get_contents. I have also tried cURL and got the same response. Thanks for any help you provide.

来源:https://stackoverflow.com/questions/40662779/google-distance-matrix-api-error-invalid-request

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