0

Google Distance Matrix API からの応答を取得するために PHP でリクエストを作成する次のコードがあります。

//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();

このコードを実行すると、次の応答が返されます。

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

しかし、上記の応答から URL をコピーしてブラウザに貼り付けると、問題が発生します。次の応答が返されます。

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

誰かが同様の問題を抱えていて、なぜこれが当てはまるのか知っていますか? URL を変更しようとしましたが、file_get_contents ではなくブラウザーで機能するというのは意味がありません。cURL も試してみましたが、同じ応答が得られました。ご協力いただきありがとうございます。

4

0 に答える 0