【问题标题】:How to calculate distance between two cities using google maps api V3 [closed]如何使用谷歌地图api V3计算两个城市之间的距离[关闭]
【发布时间】:2011-11-17 07:09:22
【问题描述】:

如何计算行驶距离?

我找不到有效的示例,有人可以帮助我吗?

谢谢。

编辑: 更多信息:

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

【问题讨论】:

标签: javascript google-maps distance


【解决方案1】:

您想要的是距离矩阵 API。也就是说,如果你真的结合谷歌地图使用它。请注意,如果您在页面某处未将其与 Google 地图一起使用,Google 会禁止使用此 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 - Distance Matrix section 中找到的适合您个人口味的谷歌示例版本

【讨论】:

  • 如果您进行以下更新,这将起作用:起源:[起源],目的地:[目的地],
  • @Michael,好眼力,感谢您的指正。对于任何感兴趣的人,这里有一个fiddle,在我处理的时候会进行更正。
  • 很好,很好的例子,效果很好。
  • 如何通过多个目的地?
  • TypeError: response.rows[0].elements[0].distance is undefined 这是我使用此代码时遇到的错误。
猜你喜欢
  • 2010-12-02
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多