Ionic Native Geolocation Promise always pending - android

I created a simple app which should locate device on google maps.
My code follows official docs -
https://ionicframework.com/docs/native/geolocation/.
When I run ionic in browser (with ionic serve) it works as expected, no errors.
But when I run my app on real android device the promise never resolved nor rejected, though I am sure permission for location is granted.
this.geostate = 'asking';
this.geolocation.getCurrentPosition().then((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
this.geostate = 'coordinates ready';
processCoordinatesSomehow(latitude, longitude);
}).catch((error) => {
this.geostate = 'error';
console.log('Error getting location', error);
});
In browser it switches as expected.
But on android it always the same this.geostate === 'asking'.
For experiment reasons, in android settings for my app I set location permission to 'ask' mode.
When I tried to get location via calling appropriate method my smartphone showed me modal window asking for location permission.
I granted it, but nothing happened - this.geostate === 'asking'.
Why promise from geolocation not resolved nor rejected on android but works fine in browser?
*rebuild app not helped at all

Related

Expo react native doesn't request location permission

I'm building an app that needs to track user's locations for app functionality. I'm requesting user's location using expo Location
useEffect(() =>
{
(async ()=>{
var {granted}=await Location.
requestForegroundPermissionsAsync()
// if granted do something
})()
}, [])
The app asks for user's permission the first time, but if user selects "allow only this time" option,closes the app and reopens it, app doesn't ask the location permission again. How can I request permission again on app start if user previously user selected "only this time".
check the location permission first using this code in useEffect
PermissionsAndroid.check(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
);

Android not requesting permission in ionic app

I am building app that allows people to post pictures and videos, mainly trying to learn about ionic, cordova, android, and the like, but for some reason whenever I try to open a file using the cordova File plugin, it doesn't ask the user permission to access storage, and the code fails and the user is stuck on a loading screen.
The code is pretty simple, they take a video, it gets transcoded, then the transcoded file is uploaded to a firebase storage bucket. If I quit the app, go to settings->apps->my app->permissions and then manually turn on the storage permission, it works. The problem is, I need to ask the user for permission either at run time or on install, and it doesn't. Here is the code..
this.media.captureVideo().then(file => {
this.editor.transcodeVideo({
fileUri: file[0].fullPath,
outputFileType: this.editor.OutputFileType.MPEG4,
outputFileName: 'temp_test',
saveToLibrary: false,
height: 800,
width: 800,
maintainAspectRatio: false
}).then(fileUri => {
let pathIndex = fileUri.lastIndexOf('/'),
finalPath = 'file://' + fileUri.substr(0, pathIndex),
name = fileUri.substr(pathIndex + 1, fileUri.length);
this.file.readAsArrayBuffer(finalPath, name).then(file => {
//upload
}).catch(err => { console.log(err); });
});
});
However, this only works if I open up the settings on my phone, go to apps, then my app, then permissions, then enable storage manually. Is there some way to request the permission in ionic? I have searched and searched and all the answers I can find are specific to camera, or work in Java, but ionic isn't java. Thank you.
Effectively cordova-plugin-media-capture uses cordova-plugin-file, so the READ_EXTERNAL_STORAGE permission must be programatically asked.
Ionic offers native support for Android Permissions:
this.androidPermissions.hasPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status => {
if (status.hasPermission) {
this.captureVideo();
} else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
.then(status =>{
if(status.hasPermission) this.captureVideo();
});
}
}
Hope it helps.
The only thing that worked for me was the Android Diagnostic plugin. Check this post.

Xamarin Forms Labs Geolocation sample

I downloaded the source for Xamarin Forms Labs, and was trying to run the geolocator sample for the android project. When you click the Get Position button, the location message returned is "Cancelled". I tried making a new xamarin forms project in VS by following these steps: file > new project > Xamarin PCL. When I install xamarin forms labs in that project and use it, I get the same message. I can, however, get the Windows Phone example to work. I'm not sure if maybe the Android emulator that installs with Xamarin can even connect to the network on my machine or not. That would explain why it cant get the location
(This is a little late, but just submitting in case anyone finds this via a search)
Double check your platform permissions.
For Android:
You must request the following permissions within your Android Project
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
For iOS:
In iOS 8 you now have to call either RequestWhenInUseAuthorization or RequestAlwaysAuthorization on the location manager.
Additionally you need to add either the concisely named NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription to your Info.plist.
For Windows Phone:
You must set the ID_CAP_LOCATION permission.
Xamarin Forms
If you are developing a Xamarin Forms app, you could try using the Geolocator (Xamarin.Plugin) sample, just remember to add your permissions :)
Sample:
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync (timeout: 10000);
Console.WriteLine ("Position Status: {0}", position.Timestamp);
Console.WriteLine ("Position Latitude: {0}", position.Latitude);
Console.WriteLine ("Position Longitude: {0}", position.Longitude);

Redirect to location settings using cordova in android

Here is the requirements what i am trying to implement in my cordova android application
When user enters the home page check to see if the gps is enabled or not.
If not enabled i want to point the user to turn on the location settings.
first part is made easily with GPS detector plugin and second part is implemented using the web intent plugin.But its not working as i expected.
if(!gps){
//gps is disabled try to show the location setting using webintent plugin
window.plugins.webintent.startActivity(
{
action: window.plugins.webintent.ACTION_LOCATION_SOURCE_SETTINGS,
},
function() {},
function() {
alert('Failed to open URL via Android Intent.');
console.log("Failed to open URL via Android Intent. URL: " + theFile.fullPath)
}
);
}
I am getting this error Failed to open URL via Android Intent.
You can achieve this using the cordova-diagnostic-plugin. Once installed, you call it via JS something like:
cordova.plugins.diagnostic.switchToLocationSettings();
UPDATE
You can use cordova-plugin-request-location-accuracy to request high accuracy location mode (i.e. GPS) directly from within the app. This will show a native confirm dialog and if user agrees, GPS will be enabled automatically with requiring user to manually change settings:
function onRequestSuccess(success){
console.log("Successfully requested accuracy: "+success.message);
}
function onRequestFailure(error){
console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
cordova.plugins.diagnostic.switchToLocationSettings();
}
}
}
cordova.plugins.locationAccuracy.request(onRequestSuccess, onRequestFailure, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);

Phonegap/Cordova Geolocation Not working on Android 4.0+ but Working on all other platforms

I am using Phonegap version 3.30 with Phonegap build and UI elements provided by Sencha Touch. The app contains a map on the first page, the map is rendered using open street map and leaflet using a sencha touch library https://market.sencha.com/extensions/ext-ux-leafletmap .
If I set the map not to use the geolocation option which displays your location on the map then the map renders perfectly on all platforms, however when I enable the setting to use geolocation, the map renders perfectly and overlays the current location on all platforms (iOS, Android 2.0) but NOT Android 4.0+.
In fact on Android the map does not render at all which is similar behaviour to how it used to work with incorrect permissions. I have set the application to use the 3 location permissions via the Config.xml Phonegap geolocation plugin. Here is the link to the Config.xml https://www.dropbox.com/s/c1im3twg21mnxi6/config.xml
So to summarise:
Android 4.0 only with Geolocation enabled prevents map from rendering, however the map and geolocation works on all other platforms.
Does anyone know what could be causing this? I have no errors being printed to the console and as far as I can the permissions are correct and as it works on Android 2.0 I am completely stumped.
Some pictures below demonstrating the issue, please note that Geolocation also works when the app is run on a web browser.
Android Not Loading with Geolocation Enabled
iOS Loading Correctly with Geolocation
I have solved the problem, this issue happens on Android 4.2, 4.3 and 4.4.
You have to explicitly enable the following options inside your call to Ext.util.geolocation. Allow High Accuracy and Frequency. This has been a massive headache #Sencha please make this simple.
var geo = Ext.create('Ext.util.Geolocation', {
autoUpdate: false,
allowHighAccuracy: true,
frequency: '3000',
listeners: {
locationupdate: function(geo) {
var currentLat = geo.getLatitude();
var currentLng = geo.getLongitude();
var altitude = geo.getAltitude();
var speed = geo.getSpeed();
var heading= geo.getHeading();
// Ext.Msg.alert('Latitude Longitude' + currentLat + currentLng);
},
locationerror: function(geo, bTimeout, bPermissionDenied, bLocationUnavailable, message) {
if(bTimeout) {
// Ext.Msg.alert('Timeout occurred',"Could not get current position");
}
else {
// alert('Error occurred.');
}
}
}
});
geo.updateLocation();

Categories

Resources