【发布时间】:2010-02-19 12:03:51
【问题描述】:
嘿,我想知道如何使用 PHP 和 Google Maps Api 计算 2 个邮政编码之间的距离。
任何人都有任何想法或示例链接。
【问题讨论】:
标签: php google-maps
嘿,我想知道如何使用 PHP 和 Google Maps Api 计算 2 个邮政编码之间的距离。
任何人都有任何想法或示例链接。
【问题讨论】:
标签: php google-maps
假设您正在寻找geographic distance,首先您需要使用Google Maps server-side geocoding services 获取两个邮政编码的纬度和经度,如下例所示:
$url = 'http://maps.google.com/maps/geo?q=EC3M,+UK&output=csv&sensor=false';
$data = @file_get_contents($url);
$result = explode(",", $data);
echo $result[0]; // status code
echo $result[1]; // accuracy
echo $result[2]; // latitude
echo $result[3]; // longitude
然后您可以使用great-circle distance 实现来计算两个邮政编码的坐标之间的距离,如下所示:
请注意,服务器端地理编码服务只能与在 Google 地图上显示结果结合使用; Google Maps API Terms of Service License Restrictions 禁止地理编码结果而不显示在地图上。
更新:
如果您正在寻找行车距离而不是地理距离,请注意,目前没有记录和批准的方法可以通过服务器端的 HTTP 请求访问 Google Maps Directions API。
然而,返回 JSON 输出的未记录方法如下:
http://maps.google.com/maps/nav?q=from:London%20to:Dover
这将为您返回行车路线以及 JSON 格式的总行车距离:"meters":122977。
q 参数的格式应为from:xxx%20to:yyy。将 xxx 和 yyy 分别替换为起点和终点。您可以使用纬度和经度坐标而不是完整地址:
http://maps.google.com/maps/nav?q=from:51.519894,-0.105667%20to:51.129079,1.306925
请注意,这不仅没有记录,而且还可能违反Google Maps API Terms and Conditions 的限制 10.1 和 10.5。
您可能还对查看以下相关文章感兴趣:
【讨论】:
不知道 V3 API 是否有任何改变,但我已经使用了一段时间,它仍然有效:
From 和 to 分别表示为纬度、经度(地址可能会起作用; 我确定我试过了,但不记得了,反正我有坐标)
$base_url = 'http://maps.googleapis.com/maps/api/directions/xml?sensor=false';
$xml = simplexml_load_file("$base_url&origin=$from&destination=$to");
$distance = (string)$xml->route->leg->distance->text;
$duration = (string)$xml->route->leg->duration->text
【讨论】:
根据 Daniel 的回答,您可以使用 Google 的 Geocoding API 轻松获取汽车、公共交通、步行和骑自行车的距离:
$postcode1='W1J0DB';
$postcode2='W23UW';
$result = array();
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode1&destinations=$postcode2&mode=bicycling&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
print_r($result);
请务必将 &mode=bicycling 替换为您的首选参数:
【讨论】:
在这里查看邮件列表:
http://groups.google.com/group/Google-Maps-API/browse_thread/thread/71e6aa2c3de66127
一旦您决定是想要直线还是行驶距离,您就可以非常轻松地计算出来。您不必使用 PHP,但有示例。
再看看这个:
【讨论】:
Google Maps API 使用 JavaScript,而不是 PHP。为了达到您想要的效果,请将 2 个邮政编码转换为 LatLang 坐标并使用函数 distanceFrom 查找它们之间的距离。
查看this article 获取一些示例代码。
【讨论】:
这就是我在 2022 年让它发挥作用的方式:
$postcode1 = '78211';
$postcode2 = '78355';
$commute_mode = 'driving';
$api_key = 'YOUR-KEY-HERE';
$result = array();
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?key=$api_key&origins=$postcode1&destinations=$postcode2&mode=$commute_mode&language=en-EN&sensor=false";
$data = @file_get_contents($url);
$result = json_decode($data, true);
echo '<pre>';
print_r($result);
echo '</pre>';
确保获取您的 Google Maps API 并将文本 YOUR-KEY-HERE 替换为您的实际 API 密钥,并根据需要更改其他参数。 Google 每月为您提供价值高达 200 美元的免费地图加载,因此您可以轻松集成 Google Maps API 并对其进行测试,看看它是否符合您的期望。
【讨论】: