我不明白为什么我不能从函数中获取值并以角度显示在另一个函数中。我的代码:
$scope.getLatitudeLongitude = function(address) {
var geocoder = new google.maps.Geocoder();
$scope.latLng = [];
geocoder.geocode( { "address": address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location,
lat = location.lat(),
lng = location.lng();
$scope.latLng.push(lat,lng);
return $scope.latLng;
}
});
};
$scope.save = function () {
$scope.address = $scope.getAddress();
$scope.getLatitudeLongitude($scope.address).then(function(){
console.log($scope.latLng);
})
}
有什么想法吗?
答案 0 :(得分:1)
像这样添加对getLatitudeLogitude的承诺应该有效。在控制器
中也注入$q
$scope.getLatitudeLongitude = function(address) {
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
$scope.latLng = [];
geocoder.geocode( { "address": address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location,
lat = location.lat(),
lng = location.lng();
$scope.latLng.push(lat,lng);
deferred.resolve($scope.latLng);
}
else{
// geocode error
deferred.reject();
}
}
return deferred.promise;
};
$scope.save = function () {
$scope.address = $scope.getAddress();
$scope.getLatitudeLongitude($scope.address)
.then(function(latLng){
console.log(latLng);
},function(){
//log your error here;
};
};
答案 1 :(得分:0)
$scope.getLatitudeLongitude = function(address) {
var geocoder = new google.maps.Geocoder();
$scope.latLng = [];
geocoder.geocode( { "address": address }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK && results.length > 0) {
var location = results[0].geometry.location,
lat = location.lat(),
lng = location.lng();
$scope.latLng.push(lat,lng);
//return $scope.latLng; you don't need to return when the method execute the $scope will know and keep the value visible to $scope.save
}
});
};
$scope.getAddress = function(){
//perform your scope.getAddress process here and after you get your address do this
$scope.addressRecieved = addressReturned;
};
$scope.save = function () {
// $scope.address = $scope.getAddress();
$scope.address = $scope.addressRecieved;
if($scope.address !== undefined) {
$scope.getLatitudeLongitude($scope.address);
}else{
console.log('Address not defined!');
}
console.log($scope.latLng);
}
//首先触发$ scope.getAddress,你甚至可以在$ scope.getAddress方法中调用$ scope.save,以确保始终定义地址,否则此程序将无法按预期工作。 //你甚至可以使用callback例如function(){$ scope.getAddress,callback}