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!
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.
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.
$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.
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With