Question

This is my controller and one service to obtain latitud and longitud.

var moduloMapa = angular.module('BeLiga.indexMapControllers', ['google-maps']);

moduloMapa.controller('controlIndexMap', function($scope, mapService) {

    $scope.center = {
        latitude: 30,
        longitude: 20
    };
    $scope.zoom = 8;

    $scope.latitud = mapService.localizar();

});

moduloMapa.service('mapService', function() {

    this.localizar = function() {
        navigator.geolocation.getCurrentPosition(mostrar);
    };

    function mostrar(posicion) {
        /* posicion es el parametro que tiene los valores, las variables para latitud y longitud las obtenemos del parametro posicion.coords*/
        var lat = posicion.coords.latitude; //obtengo la latitud
        var lon = posicion.coords.longitude; //obtengo la longitud
        alert("Te he encontrado, estas en: " + lat + " , " + lon);
        return "lat";

    }
    ;
});

The problem is: When I look the scope variable "$scope.latitud" in the browser it's null and I dont know why.

How can I obtain latitud and longitud in $scope controller?

Im beginner in angularJS, thanks for your attention.

Was it helpful?

Solution 2

The problem is getCurrentPosition runs asynchronously.

Try it like this

moduloMapa.service('mapService', function() {
    this.localizar = function() {
        var coords = { lat: 0, lon: 0 };
        navigator.geolocation.getCurrentPosition(function(posicion) {
            cords.lat = posicion.coords.latitude;
            cords.lon = posicion.coords.longitude;
        });
        return coords;
    };    
});

And as soon as the browser gets the coords they will be available to the controller's scope.

 $scope.latitud = mapService.localizar().lat;

Update:

Sorry for the typo, I've created a working plunker here

OTHER TIPS

You should use promises to solve this.

module.service('positionService', function($q, $rootScope) {
  return {
    getPosition: function() {
      var deferred = $q.defer();
      navigator.geolocation.getCurrentPosition(function(position) {
        //console.log(position);
        $rootScope.$apply(function(){deferred.resolve(position);});
      });
      return deferred.promise;
    }
  }
});

Use the service from your controller:

positionService.getPosition().then(function(position) {
  $scope.position = position;
});

You can also directly assign the promise to your scope and Angular will automatically resolve it for you:

$scope.position = positionService.getPosition();

Take a look at this fiddle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top