我一直在使用 Google 的 DistanceMatrixService。下面的代码有效,但是,如何将另一个参数传递给回调函数或从回调中获取其中一个值?
例如:我有两个 div,我想在(Results1 和 Results2)中显示不同的结果,所以我想我需要
将另一个值传递给 GoogleMapDistance 函数,例如GoogleMapDistance(YourLatLong,DestLatLong,TheDiv)
或者
能够抓取回调外部的 ResultStr document.getElementById("Results1").innerHTML = ResultStr;
或者
将innerHTM设置为函数document.getElementById("Results1").innerHTML = GoogleMapDistance(YourLatLong,DestLatLong)的返回值;
我被困住了。我怎样才能做到这一点?它现在的样子是我只能运行一次所有这些代码,并且只写入一个 div。
<div id="Results1"></div>
<div id="Results2"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function GoogleMapDistance(YourLatLong,DestLatLong)
{
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [YourLatLong],
destinations: [DestLatLong],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status)
{
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++)
{
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++)
{
var element = results[j];
var from = origins[i];
var to = destinations[j];
var distance = element.distance.text;
var duration = element.duration.text;
var ResultStr = distance + " (<i>" + duration + "</i>)";
}
}
document.getElementById("Results1").innerHTML = ResultStr;
}
}
var YourLatLong = "45.4049,-122.797997";
var DestLatLong1 = "47.468893,-122.227978";
var DestLatLong2 = "61.221274,-149.831545";
GoogleMapDistance(YourLatLong,DestLatLong1);
</script>