如何使用Google Maps API V3计算两个城市之间的距离

11
如何计算行驶距离?

我找不到一个可行的示例,有人能帮帮我吗?

谢谢。

编辑: 更多信息:

我有两个文本输入框来输入城市。在更改时,我只想在另一个div中显示/更新距离。


相关(但不完全相同):https://dev59.com/J3I_5IYBdhLWcg3wK_o5 - yoozer8
官方API Web服务已在网上完整记录(附有示例):http://code.google.com/apis/maps/documentation/directions/ - Adam Hopkinson
1个回答

17

你所需要的是距离矩阵API。也就是说,如果你真的是在结合谷歌地图使用它。请注意,如果您没有在页面上使用谷歌地图,则谷歌禁止使用此API。

这里是距离矩阵API的基本示例:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var origin = new google.maps.LatLng(55.930385, -3.118425),
    destination = "Stockholm, Sweden",
    service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false
    }, 
    callback
);

function callback(response, status) {
    var orig = document.getElementById("orig"),
        dest = document.getElementById("dest"),
        dist = document.getElementById("dist");

    if(status=="OK") {
        orig.value = response.destinationAddresses[0];
        dest.value = response.originAddresses[0];
        dist.value = response.rows[0].elements[0].distance.text;
    } else {
        alert("Error: " + status);
    }
}
</script>
</head>
<body>
    <br>
    Basic example for using the Distance Matrix.<br><br>
    Origin: <input id="orig" type="text" style="width:35em"><br><br>
    Destination: <input id="dest" type="text" style="width:35em"><br><br>
    Distance: <input id="dist" type="text" style="width:35em">
</body>
</html>

这是谷歌的一个示例,根据您的个人喜好进行了调整,我在Google Maps Api v3 - 距离矩阵部分找到了它。


4
如果你进行以下更新:origins: [origin], destinations: [destination],那么这个方法就会奏效。 - Michael Sallander
3
@Michael,眼力真不错,感谢纠正。如果有任何感兴趣的人,这里是一个fiddle ,我也会对其进行修正。 - uɥƃnɐʌuop
2
很棒,不错的例子,运行良好。 - Eduardo
我该如何传递多个目的地? - Keval Gangani
这是我使用这段代码时遇到的错误:TypeError: response.rows[0].elements[0].distance 未定义。 - Ankit Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接