我对Django一无所知,但是
getDistanceMatrix
回调调用可能是异步进行的。这意味着在触发第一次回调时,for循环已经完成。使用这些值生成所有回调
window.firstname
,
window.lastname
和
window.rating
那是
由上一次迭代设置
循环的一部分。
如果这确实是问题所在,您可以通过将其作为
callback
而不是参数。
for (let location = 0; location < locations.length; location++) {
// ^^^ Move the location definition inside the for-loop and use `let` instead
// of `var`. This has to do with scoping and might prevent bugs later on.
// https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example
// Use `const` (or `let`) instead of `var` see link above.
const data = {},
destination = $('#origin-input').val(),
service = new google.maps.DistanceMatrixService();
data.origin = locations[location];
data.firstname = firstname[location];
data.lastname = lastname[location];
data.rating = rating[location];
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC, // kilometers and meters.
avoidHighways: false,
avoidTolls: false
},
// forward the response and status to the callback and add your data
(response, status) => callback(response, status, data)
);
}
然后在回调中接受这些参数:
function callback(response, status, data) {
// ...
var node = document.createTextNode(`${data.firstname} ${data.lastname}`);
// ...
}
我还建议你搬家,比如
new google.maps.DistanceMatrixService()
和
$('#origin-input').val()
在for循环之外。它们不依赖于正在迭代的元素,而是根据需要创建更多的元素。(如果
locations
包含你创建的100个元素
新谷歌。地图。距离矩阵服务()
而你很可能只需要1个。)我在示例代码中忽略了这一点,因为没有必要修复代码。