我想要有一個函數來計算谷歌地圖的路線動態地更改基於從.getJSON檢索到的數據。我已經嘗試在.done函數下包含函數calcRoute()的大部分內容,但是我在javascript控制檯中收到屬性waypoint中的錯誤。我無所適從,因爲當我在.done下沒有包含函數的大部分時,數組仍然是空白的(使用.getJSON進行異步調用。下面是爲您提供更好主意的代碼:通過使用.getJSON谷歌地圖api
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var data = $.getJSON("/westcoast_map.php", {
westcoast_id: $('.opener').data('westcoast_id')
}, function(json) {
return json[1];
});
data.done(function(theData) {
waypts = theData[1];
console.log(waypts); //this spits out the array in the proper format, i.e. {location:city, state, stopover:true},...etc...
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
});
}
我不完全相信你的問題是,如果你將當前的回調函數放在'.done()'部分的回調函數(json){return json [1]; }? – 2013-03-04 11:13:57
當其他代碼運行時,數組將保持爲空,因爲它是異步的;你能給我一個代表你的意思的例子嗎? – user1072337 2013-03-05 00:30:46