我已经开始尝试使用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>
callback(response, status, item)
的主体中,又会调用另一个回调函数item(some_arg)
,是这样吗? - SASM