Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use HTML5 geolocation in angularjs

How can I use HTML5 geolocation in angularjs? I can get it using HTML5; but how can I pass it to angularjs scope in controller? any sample jsfiddle will save my day!

like image 709
AngryJS Avatar asked Apr 20 '14 17:04

AngryJS


People also ask

How does HTML5 geolocation work?

How does the HTML5 geolocation API work? HTML5 geolocation detects latitude and longitude coordinates by using the device's GPS (if available on the device) or the device's mobile/WIFI signal (if GPS is not available. The mobile/WIFI signals are triangulated to work out the latitude and longitude.

What is the geolocation API in HTML5?

The HTML Geolocation API is used to get the geographical position of a user. Since this can compromise privacy, the position is not available unless the user approves it. Note: Geolocation is most accurate for devices with GPS, like smartphones.

How does $Watch work AngularJS?

$watch(function() {}, function() {} ); The first function is the value function and the second function is the listener function. The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time.


2 Answers

I'd suggest abstracting this into a service so your controller doesn't have a dependency on window.navigator, and to avoid the unnecessary use of $scope.$apply(). Here's what I'm using in my project:

angular.module('app', []).factory('geolocationSvc', ['$q', '$window', function ($q, $window) {      'use strict';      function getCurrentPosition() {         var deferred = $q.defer();          if (!$window.navigator.geolocation) {             deferred.reject('Geolocation not supported.');         } else {             $window.navigator.geolocation.getCurrentPosition(                 function (position) {                     deferred.resolve(position);                 },                 function (err) {                     deferred.reject(err);                 });         }          return deferred.promise;     }      return {         getCurrentPosition: getCurrentPosition     }; }]); 

Then I consume it in my controller like this:

function captureUserLocation() {     geolocationSvc.getCurrentPosition().then(onUserLocationFound); } 
like image 56
Jared Avatar answered Sep 23 '22 11:09

Jared


you can do something

myApp.controller('fooCtrl', function($scope){   if (navigator.geolocation) {     navigator.geolocation.getCurrentPosition(function(position){       $scope.$apply(function(){         $scope.position = position;       });     });   } }) 

you need to do $scope.$apply to trigger the digest cycle when the geolocation arrives and to update all the watchers.

like image 34
Vlad Gurovich Avatar answered Sep 21 '22 11:09

Vlad Gurovich