我有各种客户及其地址的 $scope.contacts。我想遍历所有地址,将它们发送到 google API 并附上纬度/经度以供以后在 Google map 中使用。
这就是我目前所拥有的:
//Get already the Geodata of the selected GroupContacts
for (var p = 0; p < $scope.contacts.length;p++) {
var street = $scope.contacts[p].address;
var zip = $scope.contacts[p].postcode;
var city = $scope.contacts[p].city;
vermittlungService.getGoogleData(street,zip,city).then(function(response){
$rootScope.contacts[p].lat = response.data.results[0].geometry.location.lat;
$rootScope.contacts[p].lng = response.data.results[0].geometry.location.lng; //attach to the $scope
});
console.log($scope.contacts);
};
据我所知,异步调用中的 [p] 值已经更改了该值,因此我无法将正确的纬度/经度附加到联系人。我在控制台中收到错误“:无法读取未定义的属性‘1’”。
我怎样才能等待循环直到数据到达然后继续。
谢谢! 编辑:这是我获取 Google 数据服务
//Fetch Google API from Adress - Returns geoDataObject
this.getGoogleData = function(street,zip,city) {
return $http.get('https://maps.googleapis.com/maps/api/geocode/json?address= ' + street + '+' + zip + '+' + city + APIKEY)
.then(function(response) {
return response;
})
};
解决方案:我需要将逻辑包装在一个函数中。然后就可以了!
for (var p = 0; p < $scope.contacts.length;p++) {
(function(p) {
setTimeout(function() {
var street = $scope.contacts[p].address;
var zip = $scope.contacts[p].postcode;
var city = $scope.contacts[p].city;
vermittlungService.getGoogleData(street,zip,city,apiKey).then(function(response){
$rootScope.contacts[p].lat = response.data.results[0].geometry.location.lat;
$rootScope.contacts[p].lng = response.data.results[0].geometry.location.lng; //attach to the $scope
}, function(error){
console.log(error);
});
}, 250*p);
})(p);
});
最佳答案
你试过用匿名函数包装进程吗?
for (var p = 0; p < $scope.contacts.length;p++) {
!function() {
var street = $scope.contacts[p].address;
var zip = $scope.contacts[p].postcode;
var city = $scope.contacts[p].city;
vermittlungService.getGoogleData(street, zip, city).then(function(response) {
$rootScope.contacts[p].lat = response.data.results[0].geometry.location.lat;
$rootScope.contacts[p].lng = response.data.results[0].geometry.location.lng;
});
console.log($scope.contacts);
}();
};
关于javascript - 在for循环中循环遍历google Maps Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124248/