2017-01-24 6 views
0

場所番号を使用して$distanceの値を返すPHPコードがありますが、どのように距離を取得するのですか? は、ここにコードPHPを使用して2つの場所から距離を取得する方法

$from = "Arlington Heights, IL 60005, United States"; 
$to = 'Arlington Heights, IL 60004, United States'; 
$from = urlencode($from); 
$to = urlencode($to); 
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false"); 
$data = json_decode($data); 
$time = 0; 
$distance = 0; 

foreach($data->rows[0]->elements as $road) { 
    $time += $road->duration->value; 
    $distance += $road->distance->value; 
} 
+0

あなたは、 "位置番号" とはどういう意味ですか?私の知る限りでは、コード内に実際の場所名を使用していますか? – treegarden

答えて

0

さて、それは私がコンマの程度間違っていたように見えますが、彼らのこのクエリのために必要とあなたはユーザの入力に依存する場合に特にエラーが発生する可能性がないことを、オンボード取ります。 ABの場合は、あなたの問題はforeach()ループにあると考えています。また、それはそうではないオブジェクトのように配列を照会する。配列内の特定の要素を照会するときは角括弧[]を使用する必要があります。

$from = 'Arlington Heights, IL 60005, United States'; 
$remFrom = str_replace(',', '', $from); //Remove Commas 
$from = urlencode($remFrom); 

$to = 'Arlington Heights, IL 60004, United States'; 
$remTo = str_replace(',', '', $to); //Remove Commas 
$to = urlencode($remTo); 

$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false"); 
$data = json_decode($data, true); 

$time = $data['rows'][0]['elements'][0]['duration']['text']; //Text for String and Value for INT 
$distance = $data['rows'][0]['elements'][0]['distance']['text'];//Text for String and Value for INT 

echo 'Distance: ' . $distance . '<br>'; 
echo 'Time: ' . $time; 

出力:

Distance: 5.7 km 
Time: 11 mins 

参照:

https://developers.google.com/maps/documentation/distance-matrix/intro

+0

カンマで問題なく動作します。 'urlencode'はそれを処理します – treegarden

+0

ありがとう、しかし情報は入力テキストから来ます。どうすれば昏睡状態を取り除くことができますか? –

+0

@GhadahSalmanカンマは 'urlencode()'の後ろを通過しますが、それらは不要です。私は個人的にスペースから離れてすべての非単語の文字を削除します。上のコードは、 'str_replace()'を使ってこれを行う方法を説明しています。あなたのユーザ入力変数を含むように '$ from'と' $ to'変数を設定するだけです。 – Kitson88

関連する問題