我一直在玩Google的DistanceMatrixService。下面的代碼可以工作,但是,如何將另一個參數傳遞給回調函數或從回調中獲取其中一個值?Javascript Pass參數回調或在DistanceMatrixStatus中設置變量值
例如:我有我想要顯示(結果1和結果2)不同的結果兩個div,所以我想我需要或者
另一個值傳遞給像 GoogleMapDistance(YourLatLong,DestLatLong的GoogleMapDistance功能, 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>
謝謝!我用你的第一個解決方案去了。它效果很好。 – Soren
如果我沒有錯過第一個選擇中的點,那麼在這個'callback(response,status,item)'的主體中'會再次調用另一個回調'item(some_arg)'...不是嗎? – SASM