如何使用 Google 地图 api 计算距离

编程


你好

我正在为出租车公司构建一个软件,我想计算从上车点到下车点的距离,并将提供票价。 我怎样才能使用 PHP 实现这个目标

我尝试过的:

我已经尝试过使用 distance api 但它对我不起作用

解决方案1

假设您正在使用距离矩阵 API(而不是方向 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,则为 XML 格式) json?xml? 你需要解析的。 下面显示了一些用于解析距离矩阵 API 请求的 PHP 代码示例。 您需要的所有信息都可以在以下位置找到 距离矩阵 API 请求和响应 | 谷歌开发者[^]。

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

计算行驶距离和时间的起点。 您可以以地址、纬度/经度坐标或地点 ID 的形式提供一个或多个位置。
destinations

用于计算行驶距离和时间的一个或多个位置。
mode (选修的)
指定运输方式。 选项包括驾车、步行、骑自行车和公共交通。
units (选修的)
指定将距离表示为文本时要使用的单位系统。 选项包括公制和英制。
departure_time (选修的)
将所需的出发时间指定为自 UTC 1970 年 1 月 1 日午夜以来以秒为单位的整数。
traffic_model (选修的)
指定计算流量时间时要使用的假设。 选项包括 best_guess、悲观和乐观。

麦克风

コメント

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