Reputation: 3068
Please help...what am I doing wrong.
In my controller I have this function that calls out to google's geocoder, I am trying to embed it into a promise to get the results properly returned in the $scope. I have gone through 20 different iterations and I still can't get it to work. The functions work, I am getting results...but I can't get the results into the $scope...when trying to encapsulate the geocoder into a promise it gives me errors Cannot read property 'then' of undefined
function getPosition(thisLat,thisLon) {
// Retrieve address information based on Lat/Lng info
var q = $q.defer() ;
var thisLocation = getLL(thisLat,thisLon) ;
var addressInfo = {};
var notFound = 0 ;
geoCoder.geocode({'latLng': thisLocation}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var x=0;x<results.length;x++) {
var googleInfo = results[x].address_components ;
for (var y=0;y<googleInfo.length;y++) {
addressInfo.fullAddress = results[x].formatted_address;
q.resolve(addressInfo) ;
}
}
} else {
return q.reject("none" ) ;
}
return q.promise ;
});
}
$scope.getEntrances = function() {
for (var x=0;x<$scope.park.entrances.length;x++) {
getPosition($scope.park.entrances[x].coordinates[0],$scope.park.entrances[x].coordinates[1])
.then(function(result) {
$scope.park.entrances[x].addressInfo = result ;
}) ;
}
}
$scope.getEntrances() ;
Upvotes: 0
Views: 57
Reputation: 30400
Try returning your promise q
from the getPosition()
function itself, rather than from in the geoCoder
's callback function.
So in short, shift return q.promise;
to the end of the getPosition()
function like so:
function getPosition(thisLat,thisLon) {
// Retrieve address information based on Lat/Lng info
var q = $q.defer() ;
var thisLocation = getLL(thisLat,thisLon) ;
var addressInfo = {};
var notFound = 0 ;
geoCoder.geocode({'latLng': thisLocation}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var x=0;x<results.length;x++) {
var googleInfo = results[x].address_components ;
for (var y=0;y<googleInfo.length;y++) {
addressInfo.fullAddress = results[x].formatted_address;
q.resolve(addressInfo) ;
break; // [UPDATE] Avoid calling resolve on a promise multiple times
}
}
} else {
q.reject("none" ) ; // [UPDATE] Don't need a return statement here
}
});
// [UPDATE] return q.promise from here
return q.promise ;
}
Upvotes: 2