嗨,我想知道如何使用PHP和Google Maps API计算两个邮政编码之间的距离。
有没有人有任何想法或示例链接。
嗨,我想知道如何使用PHP和Google Maps API计算两个邮政编码之间的距离。
有没有人有任何想法或示例链接。
如果您正在寻找地理距离,首先需要使用谷歌地图服务器端地理编码服务获取两个邮政编码的纬度和经度,例如:
geographic distanceGoogle 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
您可以使用如下的大圆距离计算来计算两个邮编坐标之间的距离:
请注意,服务器端地理编码服务只能与在谷歌地图上显示结果的情况下使用;在不显示在地图上的情况下使用地理编码结果是被谷歌地图API服务条款许可限制禁止的。
更新:
如果您正在寻求驾车距离而不是地理距离,请注意,目前还没有经过记录和批准的方法可以通过服务器端的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条款和条件中的10.1和10.5限制。
您还可以查看以下相关文章:
不知道V3 API是否有任何改变,但我已经使用这个API有一段时间了,它仍然有效:
起点和终点都以纬度、经度的形式表示(地址可能也可以;我确信我试过,但我不记得了,反正我已经有了坐标)
$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
在丹尼尔的回答基础上,您可以使用谷歌的地理编码 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);
以下是我在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>';
YOUR-KEY-HERE
替换为您实际的API密钥,并根据需要更改其他参数。Google每月提供免费的地图加载,最高价值为200美元,因此您可以轻松集成Google Maps API并测试其是否符合您的期望。distanceFrom
查找它们之间的距离。