基本的谷歌地图 API 和回调

Basic google maps api and callback

本文关键字:回调 API 谷歌地图      更新时间:2023-09-26

我在使用service.getDistanceMatrix调用时遇到问题。

<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">    </script>
<script type="text/javascript">
origin = "Chicago, IL";
destination = "Springfield, IL";
service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
    origins: [origin],
    destinations: [destination],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    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.originAddresses[0];
    dest.value = response.destinationAddresses[0];
    dist.value = response.rows[0].elements[0].distance.text;
} else {
    alert("Error: " + status);
}
}
function doIt() {
origin1 = document.getElementById("orig");
destination1 = document.getElementById("dest");
service1 = new google.maps.DistanceMatrixService();

service1.getDistanceMatrix(
   {
        origins: [origin1],
        destinations: [destination1],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
    }, 
callback1
);

}
function callback1(response, status) {
if(status=="OK") {
    orig.value = response.originAddresses[0];
    dest.value = response.destinationAddresses[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">
<button onClick="doIt()">Distance</button>
</body>
</html>

其中大部分直接取自谷歌样本。但是,我正在尝试添加一个按钮来刷新表单。服务1.getDistanceMatrix中似乎出了点问题。它似乎说错误 0。

有什么想法可以解决这个问题吗?

谢谢

这些引用需要在末尾.value

service1.getDistanceMatrix(
   {
    origins: [origin1.value],
    destinations: [destination1.value],

就个人而言,我会在下面的orig, destdist中使用document.getElementById(我觉得它更安全,因为它更精确),但它的编写方式也可以。我有点困惑,因为我认为它不起作用。在上面的前callback中定义了orig, dest, dist,但我认为它们在callback1中是不可见的。

function callback1(response, status) {
if(status=="OK") {
    orig.value = response.originAddresses[0];
    dest.value = response.destinationAddresses[0];
    dist.value = response.rows[0].elements[0].distance.text;