This plugin is used for adding a geolocation plugin to the Ionic app.
Using Geolocation
There is a simple way to use the geolocation plugin. We need to install this plugin from the command prompt window.
C:\Users\Username\Desktop\MyApp>cordova plugin add cordova-plugin-geolocation
The following controller code is using two methods. The first one is the getCurrentPosition method and it will show us the current latitude and longitude of the user’s device. The second one is the watchCurrentPositionmethod that will return the current position of the device when the position is changed.
Controller Code
.controller('MyCtrl', function($scope, $cordovaGeolocation) { var posOptions = {timeout: 10000, enableHighAccuracy: false}; $cordovaGeolocation .getCurrentPosition(posOptions) .then(function (position) { var lat = position.coords.latitude var long = position.coords.longitude console.log(lat + ' ' + long) }, function(err) { console.log(err) }); var watchOptions = {timeout : 3000, enableHighAccuracy: false}; var watch = $cordovaGeolocation.watchPosition(watchOptions); watch.then( null, function(err) { console.log(err) }, function(position) { var lat = position.coords.latitude var long = position.coords.longitude console.log(lat + '' + long) } ); watch.clearWatch(); })
You might have also noticed the posOptions and watchOptions objects. We are using timeout to adjust maximum length of time that is allowed to pass in milliseconds and enableHighAccuracy is set to false. It can be set to trueto get the best possible results, but sometimes it can lead to some errors. There is also a maximumAge option that can be used to show how an old position is accepted. It is using milliseconds, the same as timeout option.
When we start our app and open the console, it will log the latitude and longitude of the device. When our position is changed, the lat and long values will change.
No comments:
Post a Comment