BackgroundGeolocation not working in background but in foreground fire why? - geolocation

Team i have implemented the tracking functionality in our app and using BackgroundGeolocation but its not working in the background below we have mentioned scenario:
Case 1:
BackgroundGeolocation is fire only 1 time if i am foreground not in background below links we have used for BackgroundGeolocation :
https://www.joshmorony.com/adding-background-geolocation-to-an-ionic-2-application/
https://www.freakyjolly.com/ionic-3-get-background-device-location-using-cordova-and-ionic-native-geolocation-plugins/
i have tried above links but i got same result for me.i really stuck location issues in ionic3 as well ionic community is not supported for any query.
loadLocation(){
// foreground Tracking
var self = this;
//get user currentLocation and update user location after move move
self.watch = this.geolocation.watchPosition(options).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => {
//self.subscription = self.watch.subscribe((position) => {
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log('lat fire1.....', +position.coords.latitude);
console.log('long fire.....', +position.coords.longitude);
//set center to map and set zoom....
self.map.setCenter(latLng);
self.map.setZoom(16);
//updateDriverLocation for get driver updated location...
self.updateDriverLocation(position.coords.latitude, position.coords.longitude);
//moveMarker for ,move marker......
self.moveMarker(position);
}, (err) => {
console.log(err);
});
// Background Tracking
let config = {
desiredAccuracy: 0,
stationaryRadius: 20,
distanceFilter: 10,
debug: true,
interval: 2000
};
this.backgroundGeolocation.configure(config).subscribe((location) => {
alert('dddddd');
console.log('BackgroundGeolocation: ' + location.latitude + ',' + location.longitude);
//updateDriverLocation for get driver updated location...
self.updateDriverLocation(location.latitude,location.longitude);
self.moveMarker(location);
}, (err) => {
console.log(err);
});
// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();
}
I tried each and everything but nothing worked please team help me.

Related

.Net Maui app completion handlers and iOS HealthKit not working with HttpClient

This works perfectly in Android.
public async Task<double> UploadData()
{
double steps = 0.0;
await _healthData.GetSteps((totalSteps) =>
{
SentrySdk.CaptureMessage("totalSteps = " + totalSteps);
MainThread.BeginInvokeOnMainThread(() =>
{
steps = totalSteps;
//Task.Delay(1000);
});
});
SentrySdk.CaptureMessage("UploadData steps = " + steps);
var fitness = new Fitness();
fitness.Steps = steps;
await _restService.SaveItemAsync(fitness, true);
return steps;
}
In iOS, totalSteps is correct, but steps is still 0 when fitness.Steps = steps runs. Bottom line, I can't get the totalSteps value from inside the _healthData.GetSteps((totalSteps) operation. The Android Google Fit and iOS HealthKit API calls run with completion handlers.
At this stage, I'm just trying to figure out how to upload data (steps, calories, active minutes, distance) to my server.
Does anyone know how to make this work? I can display all the data (steps, calories, active minutes, distance) in a View using an ObservableCollection.
I got this to work by embedding the calls like so.
_healthData.GetHealthPermissionAsync((result) =>
{
if (result)
{
_healthData.FetchSteps((totalSteps) =>
{
_healthData.FetchMetersWalked((metersWalked) =>
{
_healthData.FetchActiveMinutes((activeMinutes) =>
{
_healthData.FetchActiveEnergyBurned((caloriesBurned) =>
{
var fitness = new Fitness();
fitness.Steps = totalSteps;
fitness.Calories = caloriesBurned;
fitness.Distance = metersWalked;
fitness.Minutes = activeMinutes;
_restService.SaveItemAsync(fitness, true);
});
});
});
});
}
});

Twilio Streaming lose GaussianBlurBackgroundProcessor

I tried to set GaussianBlurBackgroundProcessor (I use this post as a starting point but instead of node.js i use *.min.js in a php page). On local video it works but when I connect my video in a room, remote partecipants see my video "clean".
Someone had have my same problem?
I use min version of:
twilio-video.js 2.22.1
twilio-video-processors.js 1.0.2
This is the code:
[...]
const TWVideo = Twilio.Video;
const bg = new Twilio.VideoProcessors.GaussianBlurBackgroundProcessor({
assetsPath: '',
maskBlurRadius: 5,
blurFilterRadius: 25,
});
bg.loadModel();
const localVideo = TWVideo.createLocalVideoTrack().then(track => {
let video = document.getElementById('local-media').firstElementChild;
setProcessor(bg, track);
video.appendChild(track.attach());
$('#local-media').find('video').css('width', '200px');
});
TWVideo.connect(room_token, {
name: roomName
}).then(room => {
window.room = activeRoom = room;
log('Connected to Room '+ roomName);
room.participants.forEach(participantConnected);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
room.once('disconnected', error => room.participants.forEach(participantDisconnected));
room.on('reconnecting', error => {
assert.equal(room.state, 'reconnecting');
if (error.code === 53001) {
console.log('Reconnecting your signaling connection!', error.message);
}
else if (error.code === 53405) {
console.log('Reconnecting your media connection!', error.message);
}
});
room.on('reconnected', () => {
console.log('Reconnected your signaling and media connections!');
assert.equal(room.state, 'connected');
});
room.on('participantReconnected', remoteParticipant => {
console.log("${remoteParticipant.identity} has reconnected the signaling connection to the Room!");
assert.equals(remoteParticipant.state, 'connected');
})
});
[...]
Thanks!
The issue is that you are creating a local video track and applying the blur to it, but you’re not using that track when you connect to the room. I would create the local video track and audio track first, then apply them to the room when you connect like this:
Video.connect(roomToken, {
name: roomName,
tracks: [localVideo, localAudio]
}).then(…);

Appcelerator Geolocation never returns a speed on iOS

I'm using Appcelerator to provide a geo track. This works very well on Android, but on the iOS platform I am not getting speed or heading information from the onLocation event.
I initialise my GPS:
permissions.requestLocationPermissions(Ti.Geolocation.AUTHORIZATION_ALWAYS, function (e) {
if (e.success && !configuredMonitoring) {
if (OS_IOS) {
Ti.Geolocation.accuracy = Ti.Geolocation.ACCURACY_BEST;
Ti.Geolocation.distanceFilter = 5;
Ti.Geolocation.preferredProvider = Ti.Geolocation.PROVIDER_GPS;
Ti.Geolocation.pauseLocationUpdateAutomatically = true;
Ti.Geolocation.activityType = Ti.Geolocation.ACTIVITYTYPE_OTHER_NAVIGATION;
}
if (OS_ANDROID) {
Ti.Geolocation.Android.addLocationProvider(Ti.Geolocation.Android.createLocationProvider({
name: Ti.Geolocation.PROVIDER_GPS,
minUpdateDistance: 10,
minUpdateTime: 1
}));
Ti.Geolocation.Android.addLocationRule(Ti.Geolocation.Android.createLocationRule({
provider: Ti.Geolocation.PROVIDER_GPS,
accuracy: 10,
maxAge: 5000,
minAge: 1000
}));
Ti.Geolocation.Android.addLocationProvider(Ti.Geolocation.Android.createLocationProvider({
name: Ti.Geolocation.PROVIDER_NETWORK,
minUpdateDistance: 10,
minUpdateTime: 1
}));
Ti.Geolocation.Android.addLocationRule(Ti.Geolocation.Android.createLocationRule({
provider: Ti.Geolocation.PROVIDER_NETWORK,
accuracy: 10,
maxAge: 5000,
minAge: 1000
}));
Ti.Geolocation.Android.manualMode = true;
}
}
Then I add eventlisteners for iOS location updates being paused
if (Ti.Geolocation.locationServicesEnabled){
Ti.Geolocation.addEventListener('location', onLocation);
if (OS_IOS) {
Ti.Geolocation.addEventListener('locationupdatepaused', onLocationupdate);
Ti.Geolocation.addEventListener('locationupdateresumed', onLocationupdate);
}
}
My onLocation function runs
function onLocation(e) {
if (!e.error) {
var coords = e.coords;
console.log(JSON.stringify(e));
} else {
console.log('Error!':+JSON.stringify(e))
}
}
in my return data I see
{
"success":true,
"coords:{
"timestamp":1488757841662,
"speed":-1,
"longitude":173.2793426513672,
"floor":{"level":0},
"latitude":-41.274879455566406,
"accuracy":65,
"heading":-1,
"altitude":3.9126133918762207,
"altitudeAccuracy":10
},
"code":0,
"bubbles":true,
"type":"location",
"source":{
"preferredProvider":null
},
"cancelBubble":false
}
I never see anything other than -1 in my speed or heading, which according to the documentation: "On iOS, a negative value indicates that the heading data is not valid."
What am I doing wrong here?
We had this same issue and were pulling our hair out trying to figure it out. Try changing Ti.Geolocation.ACCURACY_BEST to Ti.Geolocation.ACCURACY_BEST_FOR_NAVIGATION. This fixed it for us.

Cordova ionic geolocation fails : Position retrieval timed out error code 3 on iOS

I'm working on an app ios/android using cordova and ionic.
cordova plugin geolocation is in version 2.2.0.
it's working good on android.
but on ios, after receiving new position from the watcher 4 times, i have the following error :
PositionError {code: 3, message: "Position retrieval timed out.", PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}
somebody have a solution ?
here a part of my code :
var posOptions = {
timeout : 10000,
enableHighAccuracy: false
};
var watchOptions = {
timeout : 10000,
enableHighAccuracy: false // may cause errors if true
};
/**
* Sets initial user position.
*/
$ionicPlatform.ready(function () {
console.log('ready');
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
setLocationData(position);
}, function (err) {
// error
});
/**
* Watches for user position.
*/
$timeout(function() {
console.log(watchOptions);
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function (err) {
// error
console.log(watchOptions);
console.log(err);
alert(err);
},
function (position) {
console.log(watchOptions);
console.log('refresh')
alert('refresh');
setLocationData(position);
});
}, 10000);
});
I solved my issue by doing this :
when Watcher have errors. stop it and restart.
here my code :
/**
* Sets initial user position.
*/
$ionicPlatform.ready(function () {
console.log('ready');
$cordovaGeolocation
.getCurrentPosition(posOptions)
.then(function (position) {
setLocationData(position);
}, function (err) {
// error
});
/**
* Watches for user position.
*/
$timeout(function() {
console.log(watchOptions);
watchLocation();
}, 10000);
});
function watchLocation(){
var watch = $cordovaGeolocation.watchPosition(watchOptions);
watch.then(
null,
function (err) {
watch.clearWatch();
watchLocation();
},
function (position) {
setLocationData(position);
});
}
I'm really sorry that I cannot help you more but this is the code I was using in the past...
(it was a Cordova application using Phonegap build)
var getLocation = function() {
var deferred = Q.defer();
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
var onSuccess = function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
deferred.resolve({lat : lat, lng : lng});
};
var onError = function() {
var lat = -77.847635;
var lng = 166.760616;
deferred.resolve({lat : lat, lng : lng});
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
} else {
onError();
}
return deferred.promise;
};
There are plenty things that can possibly go wrong. First of all does the app ask user for permission to use the location?
In some instances it wasn't working for me - and the error codes weren't consistent - so there is a fallback to Antarctica...
I have solved by modifying the iOS Cordova Plugin (CDVLocation.m) as follow:
if (enableHighAccuracy) {
__highAccuracyEnabled = YES;
// Set distance filter to 5 for a high accuracy. Setting it to "kCLDistanceFilterNone" could provide a
// higher accuracy, but it's also just spamming the callback with useless reports which drain the battery.
//self.locationManager.distanceFilter = 5; //OLD CODE
self.locationManager.distanceFilter = kCLDistanceFilterNone; //NEW CODE
// Set desired accuracy to Best.
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
} else {
__highAccuracyEnabled = NO;
//self.locationManager.distanceFilter = 10; //OLD CODE
self.locationManager.distanceFilter = kCLDistanceFilterNone; //NEW CODE
self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
}
Source: Apache Cordova geolocation.watchPosition() times out on iOS when standing still

Google Maps JS API v3 not Geolocating with Phonegap iOS 3.5.0 and jQuery Mobile

The Setup
Currently building my phone gap iOS app which includes geolocation in addition to sending the results to a database and getting back nearby locations. Because I am using jQuery Mobile and Phonegap, I was testing on a browser to perfection, geolocation was success and everything returned was as well. On the iOS device, not so much. When sending a set latitude and longitude, everything returned successfully, but when using the google maps geolocation, and eventually the cordova plugin for geolocation, both failed as unable to find my location, even though they are the exact same code, minus the phone gap initializer on the website.
The Code
jQuery
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
$(document).ready(function () {
//Load Google Map & Geolocate
$(document).on("pagecreate", "#game", function () {
// keep as separate function call to allow for DOM to update after a tag
loadGoogleMap();
});
function loadGoogleMap() {
var defaultLatLng = new google.maps.LatLng(34.0983425, -118.3267434); //default location is Hollywood, CA
if (navigator.geolocation) {
function success(pos) {
//set fields for current user latitude and longitude
$("#lat_in").val(pos.coords.latitude);
$("#lon_in").val(pos.coords.longitude);
//location found
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
//try cordova geolocation plugin
function onSuccess(position) {
alert("CDV position success");
//alert(position.coords.latitude);
//alert(position.coords.longitude);
}
function onError(error) {
alert("CDV position error");
//alert("code: " + error.code + "\n" + "message: " + error.message);
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);
alert("CDV position fail. Google geolocate fail"); //WHERE THE ERROR IS THROWN. THIS IS ALWAYS THE OUTCOME
//drawMap(defaultLatLng); //Failed to find location. Show default location
}
//Geolocate. Cache location for 5 mins. Timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {
maximumAge: 500000,
enableHighAccuracy: true,
timeout: 6000
});
} else {
drawMap(defaultLatLng); //No geolocation support, show default map
}
function drawMap(latlng) {
//Collect Data to Send
var uname = $("#unm_in").val();
var lat = $("#lat_in").val();
var lon = $("#lon_in").val();
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
//update latitude and longitude on DB for logged in user && get nearby users
$.post("PHP_ON_SERVER", {
uname: uname,
lat: lat,
lon: lon
}, function (data) {
$.each(data, function (key, value) {
//Define variables
var allUsrLoc = new google.maps.LatLng(value.lat, value.lon);
var contentString = value.uname;
var mkrImg = "inUsrIcon.png"; //icon for logged in user
var inUserName = value.fname + " " + value.lname;
//if info belongs to current user
if (contentString === uname) {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player",
icon: mkrImg
});
//change header to name and points
$("#inUserInfo").text("Hi " + inUserName + " || You have " + value.points + " points");
//disable tag button if not it
if (value.isit === "notit") {
$("#tagBtn").addClass("ui-state-disabled");
}
}
//if not current user and is not it
else if (contentString != uname && value.isit != "it") {
var marker = new google.maps.Marker({
position: allUsrLoc,
map: map,
title: "Player"
});
google.maps.event.addListener(marker, 'click', function () {
//Change selected player hidden field to match marker
$("#unm_sel").val(contentString);
$("#lat_sel").val(value.lat);
$("#lon_sel").val(value.lon);
$("#isit_sel").val(value.isit);
//Change tag button to selected player's username
$("#tagBtn").text("Tag " + contentString);
});
}
//no condition for if not current user and is it. TBD if anything will come
});
}, "json");
} //end drawMap
} // end loadGoogleMap
}
HTML
<div data-role="content" role="main" id="map-canvas">
<!-- Map loads here -->
</div>
Some More to Know
I have been reading up on other related questions, but none of the others do work. Either they say use the plugin, which I am to no avail, or set <access origin="*" /> which I am doing already. In addition, most of the other questions revolve around pre-3.0.0 versions of phone gap, which was its own monster. Also, the map loads, just no markers display. On the DB, the user who's location is being updated is set to (0,0). Lastly, when using geolocation in any other app, the iOS device I test on is successfully finding my location. In addition, I am testing on the same WiFi network as the browser which worked, so anything relating to internally being unable to locate due to network or hardware is ruled out.
If you want to see the working example, just ask.

Resources