简体   繁体   中英

How do I pass geo location data around in Angular JS?

So basically I'm building an angular/ionic app that is heavily location based, basically every feature requires geo location of the user. I'm trying to wrap my head around providing the location data from the user to forms, controllers etc. I understand that the call to get the user's loc is like this below(which is a callback).

 Navigator.geolocation.watchPosition(function (pos) {
      var latLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
  }, function (error) {
      alert('Unable to get location: ' + error.message);
  });

Basically how do I pass around the result of this the user's location and utilize it for various other functions? Do I need to duplicate this code snippet in every place where I want the user's location("notice it's in watch mode to detect changes")

Thanks a lot.

您应该将该代码放入服务或工厂中,然后根据需要将其注入到控制器中。

Create a factory and have the promise resolve the latLng.

.factory('Local', ['$q', function($q){
  return {getLocation: function(options){
    var q = $q.defer();
    navigator.geolocation.watchPosition(function (pos) {
    var latLng = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
    q.resolve(latLng);
 }, function (error) {
  q.reject(error)
 }, options);
    return q.promise;
  }

}
}])

Then you can inject the factory into wherever you need it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM