Javascript 如何使用谷歌地图api V3计算两个城市之间的距离
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7421442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to calculate distance between two cities using google maps api V3
提问by josh2245
How to calculate the driving distance ?
如何计算行驶距离?
I'm unable to find a working example, can anybody help me ?
我找不到工作示例,有人可以帮助我吗?
Thank you.
谢谢你。
EDIT: More info:
编辑:更多信息:
I have two text inputs to type the cities. On change I just want to display/update the distance in another div.
我有两个文本输入来输入城市。在更改时,我只想显示/更新另一个 div 中的距离。
回答by DonVaughn
What you want is the Distance Matrix API. That is, if you are really using it in combination google maps. Note that Google prohibits the use of this API if you are not using it with a Google Map somewhere on the page.
你想要的是距离矩阵 API。也就是说,如果您真的在组合谷歌地图中使用它。请注意,如果您未在页面上的某处将其与 Google 地图一起使用,则 Google 禁止使用此 API。
Here's a basic example of the Distance Matrix 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>
This is a version of google's example adapted to your personal taste which I found in the Google Maps Api v3 - Distance Matrix section
这是我在Google Maps Api v3 - Distance Matrix 部分找到的适合您个人品味的 google 示例版本