Ionic 3: BackgroundLocation updates are too rare - ionic-framework

I'm currently facing a problem that is not so nice. I already created an issue but no response. I need every location change to update the camera center position. But this doesn't happen. The refresh is not definable with time. It's just very rare for my needs. Android and iOS is the same. The log is called every minute or something like that.
Also I tried the console log outside the ngZone but it's the same.
This is what my configuration code looks like:
let config = {
desiredAccuracy: 0,
stationaryRadius: 1,
distanceFilter: 0,
debug: true,
interval: 2000,
pauseLocationUpdates: false,
activityType: "AutomotiveNavigation"
};
this.backgroundGeolocation.configure(config).subscribe((location) => {
// Run update inside of Angular's zone
this.zone.run(() => {
if(this.map) {
this.map.getMyLocation().then( (userLocation: MyLocation) => {
console.log("INSIDE ZONE Google Maps Location \n LAT: " + userLocation.latLng.lat + "\nLNG: " + userLocation.latLng.lng);
this.userLocation = userLocation.latLng;
this.speed = userLocation.speed;
this.bearing = userLocation.bearing;
this.altitude = location.altitude;
this.cameraFollow();
this.notify(this.nearestReports[0]);
}).catch( error => {
alert("Background - NO GPS FOUND: " + error);
});
}
});
});
// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();

Consider using another Ionic Native plugin called Geolocation.
There is a very handy watchPosition() function in there that looks like what you are looking for. Here's an example:
let options = {
enableHighAccuracy: true,
timeout: Infinity, // don't return response until new ping is available from OS, to save battery
maximumAge: 0
};
const subscription = this.geolocation.watchPosition(options)
.filter((p) => p.coords !== undefined) //Filter Out Errors
.subscribe(position => {
console.log(position.coords.longitude + ' ' + position.coords.latitude);
});
Don't forget to stop the subscription when not needed in order to save battery:
subscription.unsubscribe();

Related

Call MapboxDirections() multiple times inside loop

I have been working with Mapbox Direction API and I am getting more than 100 of waypoints. As per Mapbox documentation I can't request more than 25 of WP to get a route, So I am calling it inside a loop of array with 25 WP chunk. Below is my sample code:
componentDidMount(waypoints) {
let wpChunks = this.chunkArray(waypoints, 25);
for (let chunk of wpChunks) {
routeArr.push(await this.callDirectionApi(chunk));
}
console.log('routeArr : ', routeArr);
}
callDirectionApi = (waypoints) => {
let directions;
directions = new MapboxDirections({
accessToken: mapboxgl.accessToken,
unit: 'metric',
profile: 'mapbox/driving',
interactive: false,
controls: false,
proximity: [88.30, 22.58]
});
this.map.on('load', (e) => {
let wpIndex = 0;
for (let ii = 0; ii <= waypoints.length-2; ii++) {
if (ii == 0) {
directions.setOrigin(waypoints[ii]);
} else {
directions.addWaypoint(wpIndex, waypoints[ii]);
wpIndex++;
}
}
directions.setDestination(waypoints[waypoints.length-1]);
directions.on('route', function(e) {
**console.log('Routes: ', e.route);**
resolve(e.route[0].geometry);
});
this.map.addControl(directions, 'top-left');
});
}
As a result, if I console.log the route output(the above bold line), I am getting same route as a response in each request inside loop.
Can anyone suggest me please am I doing anything wrong or not? Is this the right way to do so? If no, can you suggest any sample example?
Thanks
Probably the JS library doesn't work well with parallel requests. You should either adapt the code to make the requests one after another, or call the REST API directly.

it is possible to use the geolocation in the background sending the current latitude and longitude with a "setInterval" in IONIC1?

Basically I want to make a web request in second plane (for example when the cell phone is blocked, or not being used) every 4 hours to a web service that receives the current latitude and longitude. is this possible?
I have researched a lot, and apparently there is no way to do this, unless a plugin is used that detects movement and activates geolocation. for example:
https://github.com/transistorsoft/cordova-background-geolocation
my client wants the idea that every 4 hours a web service is consumed that receives the current latitude and longitude and verify the stores that are nearby in the current place
try this inside your function
let config = {
desiredAccuracy: 0,
stationaryRadius: 20,
distanceFilter: 10,
debug: true,
interval: 2000 // Set the interval to your desired time.
};
this.backgroundGeolocation.configure(config).subscribe((location) => {
console.log('BackgroundGeolocation: ' + location.latitude + ',' + location.longitude);
// Run update inside of Angular's zone
this.zone.run(() => {
this.lat = location.latitude;
this.lng = location.longitude;
});
}, (err) => {
console.log(err);
});
// Turn ON the background-geolocation system.
this.backgroundGeolocation.start();

How could I load video files from my library? Ionic 3

I observed that the Native File has not been supported by the Ionic View anymore see list here.
I am trying to get a video from my library by using Native Camera to access the videos. It can return me 3 different formats of path to my videos (DATA_URL, FILE_URI, and NATIVE_URI).reference to Native Camera here
I am currently using FILE_URI as recommended in this post. It returns something like "/storage/emulated/0/DCIM/Camera/VID_20180312_210545.mp4"
Please have a look at my code below. Aiming a better understanding, the current behavior is highlighted by comments with "//** comment ***" :
addVideoToOffer(){
this.platform.ready().then(() =>{
const options: CameraOptions = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
mediaType: this.camera.MediaType.VIDEO,
}
this.camera.getPicture(options).then((data_uri) => {
this.readVideoFileasGeneral(data_uri);
});
});
}
readVideoFileasGeneral(data_uri) {
if(!data_uri.includes('file://')) {
data_uri = 'file://' + data_uri;
}
return this.file.resolveLocalFilesystemUrl(data_uri)
.then((entry: FileEntry) => {
//***it does not get in here***
this.presentQuickToastMessage(data_uri);
return new Promise((resolve)=>{//, reject) => {
entry.file((file) => {
let fileReader = new FileReader();
fileReader.onloadend = () => {
let blob = new Blob([fileReader.result], {type: file.type});
resolve({blob: blob, file: file});
};
fileReader.readAsArrayBuffer(file);
});
})
})
.catch((error) => {
this.presentQuickToastMessage(error);
//***it presents "plugin_not_installed" here***
});
}
I understand that I am having this message because Native File is not supported anymore (maybe reason of the plugin_not_installed message). However, I still have to do this task. So, if someone has any idea of what I could be using in order to have the selected videos in a blob, it would be great!
Thanks for reading until here,
Cheers,
Roger A L
makeFileIntoBlob(uri) {
// get the correct path for resolve device file system
let pathIndex = uri.indexOf('var');
let correctPath = uri.slice(+pathIndex);
this.file
.resolveLocalFilesystemUrl((this.platform.is('ios') ? 'file:///' : '') + correctPath)
.then(entry => (<FileEntry>entry).file(file => this.readFile(file)))
.catch(err => console.log('ERROR: ', err));
}
readFile(file) {
if(file) {
const reader = new FileReader();
reader.onloadend = () => {
const blob: any = new Blob([reader.result], { type: file.type });
blob.name = file.name;
console.log(blob);
return blob;
};
reader.readAsArrayBuffer(file);
}
}
You need to get rid of the /private/ and keep file:///, so that your path goes like file:///var/
I'm currently working on something similar.. I have the video recorded with media-capture and then I can display it within a normal video html tag.. if this is all you need then this code may help you...
this.mediaCapture.captureVideo({duration: 10, quality: 0}).then(
(data: MediaFile[]) => {
if (data.length > 0) {
let originname = data[0].fullPath.substr(data[0].fullPath.lastIndexOf('/') + 1);
let originpath = data[0].fullPath.substr(0, data[0].fullPath.lastIndexOf('/') + 1);
let alerta = this.alerts.create({
buttons: ['ok'],
message: this.file.externalDataDirectory
});
alerta.then(set => set.present());
this.file.copyFile(originpath, originname, this.file.externalDataDirectory, 'video.mp4')
.then(result =>{
let videopath = this.webview.convertFileSrc(result.nativeURL)
let video = (document.getElementById('myvideo') as HTMLVideoElement).src = videopath;
.... rest of the code
The problem raise when you try to use the native File plugin... converting files with any method (readAsDataURL, readAsArrayBuffer or readAsBinaryString) will never resolve, this is a known problem with the Ionic Native File plugin but is not taken care of...
What I did is to take the ionic native Filesystem and use it to read the file, this does read the file and get you with a base64 (pretty sure as I don't specify the encoding field) and then you can handle it the way you want...
const data = Filesystem.readFile({
path: result.nativeURL
})
.then(data =>{
...handle data as base64
...rest of the code

Mapbox GL JS: Style is not done loading

I have a map wher we can classically switch from one style to another, streets to satellite for example.
I want to be informed that the style is loaded to then add a layer.
According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.
That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.
My code is:
mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [5,45.5],
zoom: 7
});
map.on('load', function () {
loadRegionMask();
});
map.on('styledataloading', function (styledata) {
if (map.isStyleLoaded()) {
loadRegionMask();
}
});
$('#typeMap').on('click', function switchLayer(layer) {
var layerId = layer.target.control.id;
switch (layerId) {
case 'streets':
map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
break;
case 'satellite':
map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
break;
}
});
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'regions.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function loadRegionMask() {
loadJSON(function(response) {
var geoPoints_JSON = JSON.parse(response);
map.addSource("region-boundaries", {
'type': 'geojson',
'data': geoPoints_JSON,
});
map.addLayer({
'id': 'region-fill',
'type': 'fill',
'source': "region-boundaries",
'layout': {},
'paint': {
'fill-color': '#C4633F',
'fill-opacity': 0.5
},
"filter": ["==", "$type", "Polygon"]
});
});
}
And the error is:
Uncaught Error: Style is not done loading
at t._checkLoaded (mapbox-gl.js:308)
at t.addSource (mapbox-gl.js:308)
at e.addSource (mapbox-gl.js:390)
at map.js:92 (map.addSource("region-boundaries",...)
at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?
1. Listen styledata event to solve your problem
You may need to listen styledata event in your project, since this is the only standard event mentioned in mapbox-gl-js documents, see https://docs.mapbox.com/mapbox-gl-js/api/#map.event:styledata.
You can use it in this way:
map.on('styledata', function() {
addLayer();
});
2. Reasons why you shouldn't use other methods mentioned above
setTimeout may work but is not a recommend way to solve the problem, and you would got unexpected result if your render work is heavy;
style.load is a private event in mapbox, as discussed in issue https://github.com/mapbox/mapbox-gl-js/issues/7579, so we shouldn't listen to it apparently;
.isStyleLoaded() works but can't be called all the time until style is full loaded, you need a listener rather than a judgement method;
Ok, this mapbox issue sucks, but I have a solution
myMap.on('styledata', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});
I mix both solutions.
I was facing a similar issue and ended up with this solution:
I created a small function that would check if the style was done loading:
// Check if the Mapbox-GL style is loaded.
function checkIfMapboxStyleIsLoaded() {
if (map.isStyleLoaded()) {
return true; // When it is safe to manipulate layers
} else {
return false; // When it is not safe to manipulate layers
}
}
Then whenever I swap or otherwise modify layers in the app I use the function like this:
function swapLayer() {
var check = checkIfMapboxStyleIsLoaded();
if (!check) {
// It's not safe to manipulate layers yet, so wait 200ms and then check again
setTimeout(function() {
swapLayer();
}, 200);
return;
}
// Whew, now it's safe to manipulate layers!
the rest of the swapLayer logic goes here...
}
Use the style.load event. It will trigger once each time a new style loads.
map.on('style.load', function() {
addLayer();
});
My working example:
when I change style
map.setStyle()
I get error Uncaught Error: Style is not done loading
This solved my problem
Do not use map.on("load", loadTiles);
instead use
map.on('styledata', function() {
addLayer();
});
when you change style, map.setStyle(), you must wait for setStyle() finished, then to add other layers.
so far map.setStyle('xxx', callback) Does not allowed. To wait until callback, work around is use map.on("styledata"
map.on("load" not work, if you change map.setStyle(). you will get error: Uncaught Error: Style is not done loading
The current style event structure is broken (at least as of Mapbox GL v1.3.0). If you check map.isStyleLoaded() in the styledata event handler, it always resolves to false:
map.on('styledata', function (e) {
if (map.isStyleLoaded()){
// This never happens...
}
}
My solution is to create a new event called "style_finally_loaded" that gets fired only once, and only when the style has actually loaded:
var checking_style_status = false;
map.on('styledata', function (e) {
if (checking_style_status){
// If already checking style status, bail out
// (important because styledata event may fire multiple times)
return;
} else {
checking_style_status = true;
check_style_status();
}
});
function check_style_status() {
if (map.isStyleLoaded()) {
checking_style_status = false;
map._container.trigger('map_style_finally_loaded');
} else {
// If not yet loaded, repeat check after delay:
setTimeout(function() {check_style_status();}, 200);
return;
}
}
I had the same problem, when adding real estate markers to the map. For the first time addding the markers I wait till the map turns idle. After it was added once I save this in realEstateWasInitialLoaded and just add it afterwards without any waiting. But make sure to reset realEstateWasInitialLoaded to false when changing the base map or something similar.
checkIfRealEstateLayerCanBeAddedAndAdd() {
/* The map must exist and real estates must be ready */
if (this.map && this.realEstates) {
this.map.once('idle', () => {
if (!this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
this.realEstateWasInitialLoaded = true
}
})
if(this.realEstateWasInitialLoaded) {
this.addRealEstatesLayer();
}
}
},
I ended up with :
map.once("idle", ()=>{ ... some function here});
In case you have a bunch of stuff you want to do , i would do something like this =>
add them to an array which looks like [{func: function, param: params}], then you have another function which does this:
executeActions(actions) {
actions.forEach((action) => {
action.func(action.params);
});
And at the end you have
this.map.once("idle", () => {
this.executeActions(actionsArray);
});
I have created simple solution. Give 1 second for mapbox to load the style after you set the style and you can draw the layer
map.setStyle(styleUrl);
setTimeout(function(){
reDrawMapSourceAndLayer(); /// your function layer
}, 1000);
when you use map.on('styledataloading') it will trigger couple of time when you changes the style
map.on('styledataloading', () => {
const waiting = () => {
if (!myMap.isStyleLoaded()) {
setTimeout(waiting, 200);
} else {
loadMyLayers();
}
};
waiting();
});

When I start the App with GPS off , and later GPS is activated, Location is not detected

I am having problems with GPS detection over Google Maps in Ionic App. When I start the App with GPS off and later I change from Settings device to GPS on, clicking by Find Me button - centerOnMe() function - the GPS is not working. The function responses always
`Error: GPS Timeout! ERROR = 3`
At the beginning I thought that was a cache problem but I have found out that is not that. It doesn´t matter the using $state.reload from the view. ¿does anyone get the same issue? Thanks for the support. I attach the function below:
$scope.centerOnMe = function() {
$ionicPlatform.ready(function() {
console.log('Click on Find Me');
if(!map) {
return;
}
$ionicLoading.show({
content: 'Getting current location...',
showBackdrop: false
});
//$state.reload('app.map');
watchPositionId = navigator.geolocation.watchPosition(function(position) {
navigator.geolocation.clearWatch(watchPositionId);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$scope.latitude = latitude;
$scope.longitude = longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
map.setCenter(geolocpoint);
});
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude
var long = position.coords.longitude
$scope.center = new google.maps.LatLng(lat, long);
$ionicLoading.hide();
console.log("GPS is enabled" + $scope.center);
}, function(err) {
// error
if (err.code == 1) { console.log('GPS disabled! ERROR = ' + err.code); }
else if(err.code == 2) { console.log('GPS is unavailable! ERROR = ' + err.code); }
else if(err.code == 3) { console.log('Error: GPS Timeout! ERROR = ' + err.code); }
$ionicLoading.hide();
}, {
enableHighAccuracy: true, timeout: 20000
}
);
});
};
You better to use this plugin,
cordova plugin add cordova.plugins.diagnostic
It will directly check whether gps is enabled or not.
Fore more details check following ionic forum issues,
Geo location timeout vs location permission error
Get Current Position not working after turning the GPS off on the device even if it turned on again?
Hopes this will help you !!