Ericel Ericel - 2 months ago 22
AngularJS Question

Angular Geolocation service returns nothing

I am trying to use the following geolocation service in my angular project to get location.
service file :

angular.module('myApp')
.service('geolocation', function ($q, $http) {
var getLocation = function() {
var defer = $q.defer();
// If supported and have permission for location...
if (navigator.geolocation) {
//
navigator.geolocation.getCurrentPosition(function(position){
var result = {latitude : position.coords.latitude , longitude : position.coords.longitude}
// Adding randomization since we are all in the same location...
result.latitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100 );
result.longitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100 );
getNearbyCity(result.latitude, result.longitude).then(function(data){
result.address = data.data.results[1].formatted_address;
defer.resolve(result);
});
}, function(error){
defer.reject({message: error.message, code:error.code});
});
}
else {
defer.reject({error: 'Geolocation not supported'});
}
return defer.promise;
}
var getNearbyCity = function (latitude, longitude){
var defer = $q.defer();
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude +',' + longitude +'&sensor=true';
$http({method: 'GET', url: url}).
success(function(data, status, headers, config) {
defer.resolve({data : data});
}).
error(function(data, status, headers, config) {
defer.reject({error: 'City not found'});
});
return defer.promise;
}
var service = {
getLocation : getLocation,
getNearbyCity: getNearbyCity
};
return service;
});


And I call it in my controller :

angular.module('myApp')

.controller('HomeCtrl', function ($scope, geolocation) {


geolocation.getLocation().then(function(result){
$scope.location = result;
console.log($scope.location);
});
});


Unfortunately the console.log() returns nothing.
What am I doing wrong here?

Answer

I don't see any issues with your code, change the request to:

'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude +',' + longitude +'&sensor=true';

Working Plunker

Comments