I am currently working on implementing reverse geocoding to retrieve the city name from latitude and longitude data.
After developing an Angular service that interacts with the Google Maps API using $http, I found myself facing challenges due to the asynchronous nature of $http within the Angular service. In order to overcome this, I had to create my own promise using $q in the service.
Although my solution is functional, I am unsure if it is the most optimal approach. Any feedback or suggestions would be greatly appreciated!
var app = angular.module('devApp', []);
app.factory('reverseGeoCoder', function($http, $q) {
var service = {
getAddress: function(lat, lng) {
var url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' +lng;
var deferred = $q.defer();
$http.get(url).then(function(data) {
// extract the address and return it to the caller
deferred.resolve(data.data.results[0].formatted_address);
}, function(reason) {
deferred.reject(reason);
});
return deferred.promise;
}
};
return service;
});
app.controller('mainController', function(reverseGeoCoder) {
var vm = this;
reverseGeoCoder.getAddress(47.353166, 8.558387).then(function(data) {
vm.address = data;
}, function(reason) {
console.log('reverse geocoding failed, reason: ' + reason);
});
});