Cordova Background GeoLocation Server Update - android

Usecase: Track associate location, as soon as he logs-in but closes the app later.
Using https://github.com/mauron85/cordova-plugin-background-geolocation plugin.
In debug mode, its showing the values, however, in the callback function, its not making the server calls.
renderMaps function calls navigator.geolocation.getCurrentPosition
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use device APIs
renderMaps();
var callbackFn = function(location) {
var data = 'longitude='+ location.longitude + '&latitude=' + location.latitude + '&id=' + vm.user_id + '&token=' + vm.accessToken;
window.longitude_sel = location.latitude;
window.latitude_sel = location.longitude;
console.log("" + data);
$.ajax({
type: "POST",
url: "https://example.com/partner/location",
data: data,
success: function(response){
console.log("RESPONSE" + response);
}
});
backgroundGeolocation.finish();
};
var failureFn = function(error) {
console.log('BackgroundGeolocation error');
};
// BackgroundGeolocation is highly configurable. See platform specific configuration options
backgroundGeolocation.configure(callbackFn, failureFn, {
desiredAccuracy: 5,
stationaryRadius: 0,
distanceFilter: 30,
interval: 60000,
stopOnTerminate: false,
startOnBoot: false,
startForeground: true,
stopOnStillActivity: false,
debug: true
});
backgroundGeolocation.start();
console.log("TEST");
}

Try this solution. Its working in my case:
$$(document).on('deviceready', function() {
cordova.plugins.backgroundMode.enable();
alert('device working!');
var userId=localStorage.getItem("userId");
if(userId!=null)
{
BackgroundGeolocation.configure({
locationProvider: BackgroundGeolocation.ACTIVITY_PROVIDER,
desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY,
stationaryRadius: 50,
distanceFilter: 50,
notificationTitle: 'Background tracking',
notificationText: 'enabled',
debug: true,
interval: 10000,
fastestInterval: 5000,
activitiesInterval: 10000,
url: 'http://example.com/index.php/locations/savebackgroundlocation',
httpHeaders: {
"Authorization": "Basic " + btoa('stack' + ":" + 'pwd#123#')
},
// customize post properties
postTemplate: {
lat: '#latitude',
lon: '#longitude'
}
});
BackgroundGeolocation.checkStatus(function(status) {
BackgroundGeolocation.start(); //triggers start on start event
});
}
});

try using 'url' option of the plugin.
don't expect your callback to work every time, as your app activity might be killed in the background by the OS, which will also kill your callback.
besides this, service should survive the kill, so if you use url option of the plugin, you can still get your updates on the server

I had to give ACCESS_BACKGROUND_LOCATION permission
In the file plugins/cordova-plugin-geolocation/plugin.xml you need to add:
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
See more here: https://developer.android.com/training/location/background

Related

How to check backgroundGeolocation started or not in phonegap

I am creating a log file, and then saving the coordinates when app run in background through backgroundGeolocation. The problem is when app runs in background mode then it's not saving the coords in log file, actually I am doing this for testing purposes that does this plugin working fine or not.
document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used!
//
function onDeviceReady() {
window.logToFile.setLogfilePath('/myapp/log.txt', function () {
backgroundGeolocation.configure(callbackFn, failureFn, {
desiredAccuracy: 10,
stationaryRadius: 20,
distanceFilter: 30,
interval: 60000
});
backgroundGeolocation.start();
}, function (err) {
// logfile could not be written
// handle error
});
var callbackFn = function(location) {
window.logToFile.debug('[js] BackgroundGeolocation callback: ' + location.latitude + ',' + location.longitude);
backgroundGeolocation.finish();
};
var failureFn = function(error) {
console.log('BackgroundGeolocation error');
};
}

React Native GeoLocation is not working on Android

Can anyone confirm if React Native Geolocation is actually working on Android?
I am stuck with location request timed out while using getCurrentPosition() method and no error message while using watchPosition() method.
I have added the required permission (FINE LOCATION) on AndroidManifest.xml and location permission is allowed for the app.
Here is my implementation:
componentWillMount() {
navigator.geolocation.getCurrentPosition((position) => {
console.log('+++++++');
console.log(position.coords.longitude);
this.setState({
longitude: position.coords.longitude,
error: null,
});
},
(error) => {
console.log(error);
},
);
}
React Native Version : 0.42
you need to change enableHighAccuracy to false
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
this.state = {
region:{}}
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position);
this.setState({
region: {
longitude: position.coords.longitude,
latitude: position.coords.latitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA
}
});
},
(error) => console.log(new Date(), error),
{enableHighAccuracy: false, timeout: 10000, maximumAge: 3000}
);
After implementing all above answers
i had to restart my new phone then it started working
Yes, location works perfectly in our React Native apps for Android.
First of all, getCurrentPosition(..) does not return a watchId. You should be using watchPosition(..) for that. Check that your device has location services enabled and if you're testing it in the emulator, that you've set a location in emulator settings. Another note: on Android M and higher, you also need to request permissions using the PermissionsAndroid.check(...) and PermissionsAndroid.request(...) API calls.
Instead of referring to the position object, just deal with the coords object.
navigator.geolocation.getCurrentPosition(
({coords}) => {
const {latitude, longitude} = coords
this.setState({
position: {
latitude,
longitude,
},
region: {
latitude,
longitude,
latitudeDelta: 0.001,
longitudeDelta: 0.001,
}
})
},
(error) => alert(JSON.stringify(error)),
// 'enableHighAccuracy' sometimes causes problems
// If it does, just remove it.
{enableHighAccuracy: true}
)
I had a similar issue to this because I was in a building which resulted to my device not being able to properly capture the gps signals. If you are in a closed building, try moving outside.
My advise to get perfect location data is to create 2 location handlers.
I use react-native-location as a first handler,
if location cant be fetched, we use the second handler using native geolocation.
Never fails, Compability:
IOS - all versions
ANDROID - all above SDK 20
Check the example below:
Configuration
RNLocation.configure({
distanceFilter: 0.5,
desiredAccuracy: {
ios: "best",
android: "highAccuracy"
},
headingOrientation: "portrait",
// Android ONLY
androidProvider: "auto",
interval: 5000, // Milliseconds
fastestInterval: 10000, // Milliseconds
maxWaitTime: 5000, // Milliseconds
// IOS ONLY
allowsBackgroundLocationUpdates: false,
headingFilter: 1, // Degrees
pausesLocationUpdatesAutomatically: false,
showsBackgroundLocationIndicator: false,
})
Function getUserLocation
static getUserLocation = async () => {
let locationSubscription: any = null
let locationTimeout: any = null
const options = { enableHighAccuracy: true, timeout: 25000 }
return new Promise<any>((resolve, reject) => {
// request permissions using RN Location
RNLocation.requestPermission({
ios: "whenInUse",
android: {
detail: "fine"
}
}).then(granted => {
console.log("Location Permissions: ", granted)
// if has permissions try to obtain location with RN location
if (granted) {
locationSubscription && locationSubscription()
locationSubscription = RNLocation.subscribeToLocationUpdates(([locations]: any) => {
locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location fetched with RN Geolocation")
resolve({ coords: { latitude: locations.latitude, longitude: locations.longitude }})
})
} else {
locationSubscription && locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("no permissions to obtain location")
resolve(null)
}
// if RN Location cant resolve the request use Native Location instead
locationTimeout = setTimeout(() => {
navigator.geolocation.getCurrentPosition((locations) => {
locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location fetched with Native Geolocation")
resolve(locations)
}, error => {
locationSubscription && locationSubscription()
locationTimeout && clearTimeout(locationTimeout)
console.log("location error", error)
resolve(null)
}, options);
}, 15000)
})
})
}
cd android
gradlew clean
dependencies
"react-native": "0.62.0",
"#react-native-community/geolocation": "^2.0.2",
Better if you try this code, I have tested in Android OS 8, RN 0.49.5
React Native current location
the trick is to set
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }

React Native Android location request timed out

In IOS there isn't a problem while looking for gps coords. It works fine.
On Android side its not stable as IOS. This problem both in real device and emulator. Sometimes it can find location, but sometimes not. Looking for 3days but there wasn't find a solution.
When my app cannot find my location, I tried via Google Maps app, it works like charm.
Here is my code for both IOS and Android;
getCurrentPosition() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({ initialPosition: position });
alert(JSON.stringify(position))
var coords = new Coords();
coords.Latitude = position.coords.latitude;
coords.Longitude = position.coords.longitude;
this.getPharmaciesByCoordinates(coords);
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
this.watchID = navigator.geolocation.watchPosition((position) => {
this.setState({ initialPosition: position });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
}
Any kind of solution is welcome.
Thanks
I removed maximumAge: 3600000 on Android and it working
It's possible that you are inside of the building or office and your signal is not that good. I've tried with many configuration and this one fit the best for me:
{
enableHighAccuracy: false,
timeout: 5000,
maximumAge: 10000
}
Or try increasing timeout. Because for me the usual 2000ms wasn't working, I kept getting "Location request timed out". So disable high accuracy, increase timeout and you're good to go.
import Geolocation from '#react-native-community/geolocation';
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
console.log(initialPosition);
},
error => Alert.alert('Error', JSON.stringify(error)),
{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
This function work for me and I have change the "AndroidManifest.xml" file with the
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Hi I was facing same issue "request time out ".
I have tried every possible solution which I found but, those could not work for me but recently I found one module which overcomes this problem.
react-native-geolocation-service
This worked for me .....
For those who still facing the issue, be aware of the params. I used to leave params to defaults but when it comes to enableHighAccuracy, you should be careful because when you set this to false, that means you are requesting WIFI location else GPS location. If you don't set this true, you will probably receive error on emulators as I did.
Supported options:
timeout (ms) - Is a positive value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. Defaults to INFINITY.
maximumAge (ms) - Is a positive value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device will always return a cached position regardless of its age. Defaults to INFINITY.
enableHighAccuracy (bool) - Is a boolean representing if to use GPS or not. If set to true, a GPS position will be requested. If set to false, a WIFI location will be requested.
Detailed Documentation
Edit 1;
I recommend you all to use this library instead of native one (react-native-geolocation-service) as its created for such timeout issues.
Remove Param 'maximumAge' & Just Keep
{ enableHighAccuracy: true, timeout: 2000}
I found a solution via external lib that uses native LocationManager. It uses play services location and emitting location event as I want.
Here is the library;
https://bitbucket.org/timhagn/react-native-google-locations#readme
And when compiling for android, don't forget to include android/app/build.gradle
dependencies {
...
compile "com.google.android.gms:play-services:10.0.1" -> which version that you have write down here.
...
}
And finally don't forget to download Google Play Services and Google Support Library in Android SDK Manager you can find your play services versions into;
<android-sdk-location>/<sdk-version>/extras/google/m2repository/com/google/android/gms/play-services
I have done the app by location request. The command
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }, will work on iOS but not in Android. I think you should check Platform.
navigator.geolocation.getCurrentPosition(
(location) => {
console.log('location ', location);
if (this.validLocation(location.coords)) {
this.locationToAddress(location.coords);
}
},
(error) => {
console.log('request location error', error);
},
Platform.OS === 'android' ? {} : { enableHighAccuracy: true, timeout: 20000, maximumAge: 10000 }
);
I tried various methods and npm modules. Finally I got solved this issue by using this module. I strongly suggest this.
https://www.npmjs.com/package/react-native-geolocation-service
In my case it worked fine after removing timeout and maximumAge and setting enableHighAccuracy to false.
Working
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Add Permission in P list and android Manifest also
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 },
// { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
I suggest to 2 ways to consider dealing with it:
Use react-native-geolocation-service - a package that suppose to deal with that problem.
Try to call once with enableHighAccuracy=true and if it fails try to call it again with enableHighAccuracy=false.
Details: It seems enableHighAccuracy=true try fetching the location via the GPS - when enableHighAccuracy=false the device first try fetching the location via Wifi and if it fails it try to fetch it via the GPS.
Here is how I've implemented number 2:
import Geolocation from "#react-native-community/geolocation";
const getCurrentLocation = (resolve, enableHighAccuracy, onError) => {
console.log(`[getCurrentPosition] enableHighAccuracy=${enableHighAccuracy.toString()}`);
Geolocation.getCurrentPosition(
(position) => {
const location = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
console.log('[getCurrentPosition] success');
resolve(location);
},
onError,
{enableHighAccuracy, timeout: 20000}
);
};
/**
* We first try to get location with enableHighAccuracy=true (try to get position via GPS) if it fails try to get it with enableHighAccuracy=false (try to get position from wifi)
* #return {Promise}
*/
export const getCurrentPosition = () => {
return new Promise((resolve) => {
getCurrentLocation(resolve, true,
(error1) => {
// failed to retrieve with enableHighAccuracy=true - now try with enableHighAccuracy=false
console.log(`[getCurrentPosition] failed 1st time trying again with enableHighAccuracy=false, error: ${error1.message}`);
getCurrentLocation(resolve, false, (error2) => {
// Could not retrieve location - we can live with that
console.log(`[getCurrentPosition] failed ${error2.message}`);
resolve();
})
});
});
}
i was stuck for 3 days but all in vain then
i just change timeout to value 20000ms.
now problem is resolved.
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 20000,
just change/Increase "timeout" value your problem will resolve.
You might want to check if your android emulator GPS is enabled or not.
Go to options ( "⋮" on emulator) --> Location --> Enable GPS signal should be enabled.
Removing timeout and maximumAge did solve the issue on android on my end
the tricks is, if you set
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }
then it will work. full code below.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class GeolocationExample extends Component {
constructor(props) {
super(props);
this.state = {
latitude: null,
longitude: null,
error: null,
};
}
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null,
});
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 },
);}
render() {
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Latitude: {this.state.latitude}</Text>
<Text>Longitude: {this.state.longitude}</Text>
{this.state.error ? <Text>Error: {this.state.error}</Text> : null}
</View>
);
}
}
export default GeolocationExample;

Location Service using Cordova

I want to check the location and store the required data in the internal storage of the mobile. To stop this task, use has to tap stop button in the main ui. As this task started, no matter the state of the app, that task should do its work.
I can implement this using native android command. But I want to implement this using cordova and I can't figure out a way to do this..
If this task cannot be done using cordova, can I do it using native android and inject to the cordova app..??
Please help..
You can do this using the ng-cordova geolocation watcher, it watches geolocation properties such as lat, lon, and speed.
first intall ng-cordova and inject it
bower install ngCordova
angular.module('myApp', ['ngCordova'])
then install the geolocation plugin
cordova plugin add org.apache.cordova.geolocation
then you want to create a watcher, make sure to fire it after a device ready event or it will cause problems
This is what device ready function looks like
document.addEventListener("deviceready", function () {
$cordovaPlugin.someFunction().then(success, error);
}, false);
here is the watcher controller:
module.controller('GeoCtrl', function($cordovaGeolocation) {
var watchOptions = {
frequency : 1000,
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
var long = position.coords.longitude
});
watch.clearWatch();
// OR
$cordovaGeolocation.clearWatch(watch)
.then(function(result) {
// success
}, function (error) {
// error
});
});
As you watch their geolocation info you can push it into a local database like http://pouchdb.com/ or couch db or a server database. If you want to use this in any state of the app you can make it into a service,
here is an example in a app i built
service.watchSpeed = function () {
console.log('watcher');
ionic.Platform.ready(function () {
var watchOptions = {
frequency: 15 * 60 * 1000,
timeout: 1 * 60 * 1000,
enableHighAccuracy: true // may cause errors if true
};
service.watch = $cordovaGeolocation.watchPosition(watchOptions);
service.watch.then(
null,
function (err) {
service.watchSpeed();
},
function (position) {
if (service.maxspeed.ToUseApp !== 0) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var speed = position.coords.speed;
service.speed = speed;
if (speed > service.maxspeed.ToUseApp) {
$state.go('overspeed');
}
if ($ionicHistory.currentStateName() === 'overspeed' && speed < service.maxspeed.ToUseApp) {
$ionicHistory.goBack();
}
} else {
console.log('speed watcher has been killed, why master??');
}
});
});
};
then in my home controller i call the watcher
ionic.Platform.ready(function () {
ffService.getMaxSpeed();
});

Cant find user location when apk installed on android phone

I have created an ionic angularjs ngCordova mobile app, wherein I have used ngCorodova geolocation plugin in order to get user location. when I am testing this on browser it works fine. but when same I [android-app.apk] I install on mobile app [obviously after checking "unknown sources" option]; I am not able to get the location. I see in app setting, permission is there to access location on mobile. Also, When event is trigerred it shows GPS symbol on top bar but it disappears.
Can anybody help me with this?
Below is the code for location in my controller.js
.directive('reverseGeocode', function ($cordovaGeolocation, $rootScope) {
return {
restrict: 'E',
template: '<div></div>',
link: function (scope, element, attrs) {
var geocoder = new google.maps.Geocoder();
var posOptions = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
// console.log(angular.toJson($rootScope.lati) + " - " );
var request = new XMLHttpRequest();
var method = 'GET';
//var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=true';
var async = true;
//alert(url);
//request.open(method, url, async);
//alert(angular.toJson(request.open(method, url, async)));
// var data = JSON.stringify(request.responseText);
// alert(JSON.stringify(request.responseText));
var latlng = new google.maps.LatLng(lati, longi);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
//alert(results[1].address_components[1].long_name);
$rootScope.colony = results[1].address_components[1].long_name;
//alert(results[1].address_components[1].long_name);
//alert(results[1].address_components[1].long_name);
//alert(angular.toJson(results[1].address_components[1].long_name));
element.text(results[1].formatted_address);
} else {
element.text('Location not found');
}
} else {
element.text('Geocoder failed due to: ' + status);
}
});
}, function(err) {
// error
});
var watchOptions = {
frequency : 1000,
timeout : 3000,
enableHighAccuracy: false // may cause errors if true
};
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function(err) {
// error
},
function(position) {
var lat = position.coords.latitude
alert("abc >>" + lat);
var long = position.coords.longitude
});
watch.clearWatch();
// OR
$cordovaGeolocation.clearWatch(watch)
.then(function(result) {
// success
}, function (error) {
// error
});
},
replace: true
}
})
In html file I am using it as :
<h6>
User Colony: {{ colony }}
<reverse-geocode lat={{lati}} lng={{longi}}></reverse-geocode>
</h6>
<a href="#" ng-click="showStores(colony)" class="button button-block button-positive">
Browse Store
</a>
which triggeres the directive and find lat and long of user.
When testing on browser, it works perfectly but not on mobile itself.
In android it is super complicated to work with the GPS user, remember that often the geolocation we get is from the browser and not the GPS itself, and this varies a lot in the devices. For your help, I recommend installing cordova.plugins.diagnostic
function onDeviceReady() {
cordova.plugins.diagnostic.isLocationAuthorized(function(enabled){
//alert("gps es : " + (enabled ? "enabled" : "disabled"));
}, function(error){
//alert("error: "+error);
});
cordova.plugins.diagnostic.isLocationEnabled(function(enabled){
if(!enabled){
alert("gps not actived");
}else{
navigator.geolocation.getCurrentPosition(onSuccess, onError, {enableHighAccuracy: true,timeout: 5000,maximumAge: 5000});
}
}, function(error){
console.log("The following error occurred: "+error);
});
}
Always trying to see if I can get a latitude and longitude and if that is not activated or not you can get, it sends a message to the user. I hope it helps you.

Categories

Resources