【解決方法】GoogleマップAPIを使用して距離を計算するにはどうすればよいですか

プログラミングQA


こんにちは

私はタクシー会社用のソフトウェアを構築していて、乗車場所から降車場所までの距離を計算し、運賃を提供したいと考えています。 PHPを使用してこれを実現するにはどうすればよいですか

私が試したこと:

すでに距離APIを使用しようとしましたが、うまくいきません

解決策 1

Distance Matrix API (Directions API ではなく) を使用していると仮定すると、リクエストの形式は次のようになります。

https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters

コードは次のようになります。

https://maps.googleapis.com/maps/api/distancematrix/json?destinations=New%20York%20City%2C%20NY&origins=Washington%2C%20DC%7CBoston&units=imperial&key=YOUR_API_KEY

明らかに、「YOUR_API_KEY」を、請求先アカウントの設定が必要な Google の API キーに置き換える必要があります。 Maps Javascript API 有効になりました。 オプションのパラメーターの完全なセットについては、以下で説明します。 JSON 形式 (または XML に置き換える場合) で応答を受け取ります。 json?xml? 解析する必要があるということ。 距離行列 API リクエストを解析するための PHP コードの例を以下に示します。 必要な情報はすべて次のサイトで見つけることができます。 距離行列 API リクエストとレスポンス | 開発者向け Google[^]。

PHP
<?php
// We need to get the JSON response into a string variable $jsonResponse
// First assign the URL of the Distance Matrix API request to a string
$url = 'href="https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters';

// Use file_get_contents() to send a GET request to the URL
$jsonResponse = file_get_contents($url);

// Decode the JSON response
$data = json_decode($jsonResponse, true);

// Check if the status is OK
if ($data['status'] == 'OK') {
    // Loop through each row (origin-destination pair)
    foreach ($data['rows'] as $row) {
        // Loop through each element (information about the origin-destination pair)
        foreach ($row['elements'] as $element) {
            // Check if the status is OK
            if ($element['status'] == 'OK') {
                // Get the distance and duration
                $distance = $element['distance']['text'];
                $duration = $element['duration']['text'];

                // Print the distance and duration
                echo "Distance: $distance\n";
                echo "Duration: $duration\n";
            } else {
                echo "Error: " . $element['status'] . "\n";
            }
        }
    }
} else {
    echo "Error: " . $data['status'] . "\n";
}
?>

距離行列 API リクエスト:
https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters

どこ outputFormat どちらかも知れません json または xml

そして parameters 含む :

origins

移動距離と時間を計算するための開始点。 1 つ以上の場所を、住所、緯度/経度の座標、または場所 ID の形式で指定できます。
destinations

移動距離と時間を計算する 1 つ以上の場所。
mode (オプション)
転送モードを指定します。 オプションには、車、徒歩、自転車、交通機関が含まれます。
units (オプション)
距離をテキストとして表現するときに使用する単位系を指定します。 オプションにはメートル法とインペリアル法が含まれます。
departure_time (オプション)
希望する出発時刻を、協定世界時 (UTC) 1970 年 1 月 1 日午前 0 時からの秒数で整数で指定します。
traffic_model (オプション)
交通時間の計算時に使用する仮定を指定します。 オプションには、best_guess、pessimistic、optimistic が含まれます。

マイク

コメント

タイトルとURLをコピーしました