Moving to another screen after loading screen finishes - android

In my react native application, in home screen there is a button to open a compass that shows the direction of a specific location. For that I need the coordinates of the user to be passed to the compass screen to make the calculations, m passing the values in the navigator.
Iam loading the coordinates on componentDidMount() method of home screen, my problem is that getting the coordinates of the user sometimes takes a bit of time (depending on the user's gps signal strength and his/her device), so I used conditional render to show a "loading" component if the user presses on compass button before coordinates are loaded. But the problem is that m not knowing how to send him/her to compass screen after the loader, because right now after the loader he/she stays in home screen, and has to press the button again to go to the compass.
state = {
currentLongitude: "unknown",
currentLatitude: "unknown",
locationLoading: false,
};
getCards = () => [...
{id: "3",
card: this.languageCard("Compass"),
onPress: () => {
this.state.currentLatitude != "unknown"
? this.props.navigation.navigate("Compass", {
latitude: this.state.currentLatitude,
longitude: this.state.currentLongitude,
})
: this.setState({ locationLoading: true });
},
}...]
componentDidMount() {
this.requestLocation();
}
requestLocation() {
var that = this;
if (Platform.OS === "ios") {
this.callLocation(that);
} else {
async function requestLocationPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Location Access Required",
message: "This App needs to Access your location",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
that.callLocation(that);
} else {
alert("Permission Denied");
}
} catch (err) {
alert("err", err);
console.warn(err);
}
}
requestLocationPermission();
}
}
callLocation(that) {
Geolocation.getCurrentPosition(
(position) => {
const currentLongitude = JSON.stringify(position.coords.longitude);
const currentLatitude = JSON.stringify(position.coords.latitude);
that.setState({ currentLongitude: currentLongitude });
that.setState({ currentLatitude: currentLatitude });
this.setState({ locationLoading: false });
},
(error) => alert(error.message),
{ enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 }
);
}
render() {
return this.state.locationLoading ? (
<Loader />
) : (
<SafeAreaView>
....
</SafeAreaView>

Related

GeoLocation React Native

I am trying to get the user location my code is working fine in the
ios and in the android it does not throw the error when user denies
the location permission.
AppState.addEventListener('change', this._handleAppStateChange);
this.geoFailure, geoOptions);
this.refresh();
}
geoSuccess = (position) => { //Success callback when user allow the
location
this.setState({
ready:true,
where: {lat:
position.coords.latitude,lng:position.coords.longitude }
})
}
geoFailure = (err) => { // i am not getting any error when user
denies the location permission in the
case of android.
this.setState({error: err.message});
console.log("Errror",err)
console.log(err.message)
if(err.message='User denied access to location services'&&Platform.OS==='ios'){
this.props.screenName==='SPLASH'&&!this.state.ready?NavigatorService.navigate(LOCATION_PERMISSION):null;
}
}
refresh=()=> // Refreshing the list when the AppState becomes
active
let geoOptions = {
enableHighAccuracy: false,
timeout: 30000,
maximumAge: 60 * 60 * 24
};
this.setState({ready:false, error: null });
navigator.geolocation.getCurrentPosition( this.geoSuccess, this.geoFailure, geoOptions);
}
I am able to navigate the user to another screen in the case of ios
if it doesn't provide the location permissions but in the case of
the android it does not giving any error when user does not provide
the location.
I am not getting how to do it , i am new to the react native.
I am not getting, what i am doing wrong.
Any help would be appreciated.
use PermissionsAndroid
import {
PermissionsAndroid
} from 'react-native';
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
(position) => {
addLocation(position.coords);
},
(error) => {
console.error(error);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 },
);
} else {
console.log('location permission denied');
}

Mock GPS location on android hardware - React Native

I have tried using applications like 'Fake GPS' and enabled Mock Locations in developer options to mock location. My location is successfully changed on google maps but the react native geolocation.getCurrentPosition is still returning me my actual true location.
Also, when calling geolocation.getCurrentPosition after different interval I'm getting response with the same timestamp. What's the reason?
getLocation() {
navigator.geolocation.getCurrentPosition(
position => {
if (this.state.inRide === false) {
console.log('setting start coord');
this.setState(
{ startLat: position.coords.latitude, startLong: position.coords.longitude },
() => this.afterStartLocationSuccess()
);
} else if (this.state.inRide === true) {
console.log('setting end coord');
this.setState(
{ endLat: position.coords.latitude, endLong: position.coords.longitude },
() => this.afterEndLocationSuccess()
);
}
console.log(position);
},
error => Alert.alert('Try again! GPS not working')
// Not using third argument.
// { enableHighAccuracy: false, timeout: 10000, maximumAge: 1000 }
);
}
This is the console log:

React native geolocation getCurrentPosition no reponse (android)

I have read and tested a lot of issues but I still can not get geolocation on Android.
I use navigator.geolocation.getCurrentPosition, on iOS everything works fine, but on Android I have no answer to this function, either success or error.
I have installed react-native-permissions to make sure that the user has activated the permissions but it does not change anything because it says that everything is "authorized".
I noticed that it came from GPS of the device. If I activate it manually, everyting works fine. However, I can not find a way to activate it for the user. On iOS, if GPS is not activated, I fall in the error callback and tell user to activate it, but on android, nothing is happennig.
I don't understand why I can't get geolocation only with getCurrentPosition (I have ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION in manifest).
Here a part of my code:
componentDidMount() {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus('location')
.then((response) => {
if (response !== "authorized") {
Alert.alert(
"Error",
"We need to access to your location",
[
{
text: "Cancel",
onPress: () => {
// do my stuff
}, style: 'cancel'
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings()
}
]
);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
}
Does anyone have any idea ?
Thank you
You should need to enable GPS on android
For enabling location/gps on Android I can recommend this module:
https://github.com/Richou/react-native-android-location-enabler
It is using the standard Android dialog for location:
like this
import React, { Component } from "react";
import { Text, StyleSheet, View, Platform } from "react-native";
import RNAndroidLocationEnabler from "react-native-android-location-enabler";
export default class index extends Component {
componentDidMount() {
this.getLocation();
}
onLocationEnablePressed = () => {
if (Platform.OS === "android") {
RNAndroidLocationEnabler.promptForEnableLocationIfNeeded({
interval: 10000,
fastInterval: 5000,
})
.then((data) => {
this.getLocation();
})
.catch((err) => {
alert("Error " + err.message + ", Code : " + err.code);
});
}
};
getLocation = () => {
try {
navigator.geolocation.getCurrentPosition(
(position) => {
//do my stuff with position value
},
(error) => {
Permissions.getPermissionStatus("location").then((response) => {
if (response !== "authorized") {
Alert.alert("Error", "We need to access to your location", [
{
text: "Cancel",
onPress: () => {
// do my stuff
},
style: "cancel",
},
{
text: "Open Settings",
onPress: () => Permissions.openSettings(),
},
]);
} else {
// do my stuff
}
});
},
{ enableHighAccuracy: true, timeout: 2000, maximumAge: 1000 }
);
} catch (error) {
this.onLocationEnablePressed();
}
};
}

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 }

Geolocation on Android with google maps v3 & jQuery Mobile

I followed this tutorial http://www.mobiledevelopersolutions.com/home/start/twominutetutorials/tmt4part1 and i have one problem. The geolocation doesn't work on the default Android browser. It does work on Chrome, IE and Chrome for Android. But not the default Android browser.
I think i have to put { enableHighAccuracy: true } somewhere put i can't get it figured out.
This is the code:
var mapdata = { destination: new google.maps.LatLng(51.3704888, 6.1723862) };
// Home page
$('#page-home').live("pageinit", function() {
$('#map_square').gmap(
{ 'center' : mapdata.destination,
'zoom' : 12,
'mapTypeControl' : false,
'navigationControl' : false,
'streetViewControl' : false
})
.bind('init', function(evt, map) {
$('#map_square').gmap('addMarker',
{ 'position': map.getCenter(),
'animation' : google.maps.Animation.DROP
});
});
$('#map_square').click( function() {
$.mobile.changePage($('#page-map'), {});
});
});
function fadingMsg (locMsg) {
$("<div class='ui-overlay-shadow ui-body-e ui-corner-all fading-msg'>" + locMsg + "</div>")
.css({ "display": "block", "opacity": 0.9, "top": $(window).scrollTop() + 100 })
.appendTo( $.mobile.pageContainer )
.delay( 2200 )
.fadeOut( 1000, function(){
$(this).remove();
});
}
//Create the map then make 'displayDirections' request
$('#page-map').live("pageinit", function() {
$('#map_canvas').gmap({'center' : mapdata.destination,
'mapTypeControl' : true,
'navigationControl' : true,
'navigationControlOptions' : {'position':google.maps.ControlPosition.LEFT_TOP}
})
.bind('init', function() {
$('.refresh').trigger('tap');
});
});
$('#page-map').live("pageshow", function() {
$('#map_canvas').gmap('refresh');
});
// Request display of directions, requires jquery.ui.map.services.js
var toggleval = true; // used for test case: static locations
$('.refresh').live("tap", function() {
// START: Tracking location with device geolocation
if ( navigator.geolocation ) {
fadingMsg('Using device geolocation to get current position.');
navigator.geolocation.getCurrentPosition (
function(position ) {
$('#map_canvas').gmap('displayDirections',
{ 'origin' : new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
'destination' : mapdata.destination, 'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
{ 'panel' : document.getElementById('dir_panel')},
function (result, status) {
if (status === 'OK') {
var center = result.routes[0].bounds.getCenter();
$('#map_canvas').gmap('option', 'center', center);
$('#map_canvas').gmap('refresh')
} else {
alert('Unable to get route');
}
}
);
},
function(){
alert('Unable to get location');
$.mobile.changePage($('#page-home'), { });
});
} else {
alert('Unable to get location.');
}
// END: Tracking location with device geolocation
$(this).removeClass($.mobile.activeBtnClass);
return false;
});
// Go to map page to see instruction detail (zoom) on map page
$('#dir_panel').live("tap", function() {
$.mobile.changePage($('#page-map'), {});
});
// Briefly show hint on using instruction tap/zoom
$('#page-dir').live("pageshow", function() {
fadingMsg("Tap any instruction<br/>to see details on map");
});
Thx for the help!
This is how you may need to call.
navigator.geolocation.getCurrentPosition(successCallback,
errorCallback,
{maximumAge:Infinity, timeout:0, enableHighAccuracy: true });
Ofcourse here you can change maximumAge and timeout values, but this is where you set enableHighAccuracy.
So just specify this as third param in your getcurrentposition method.
EDIT :
navigator.geolocation.getCurrentPosition (
function(position ) {
$('#map_canvas').gmap('displayDirections',
{ 'origin' : new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
'destination' : mapdata.destination, 'travelMode' : google.maps.DirectionsTravelMode.DRIVING},
{ 'panel' : document.getElementById('dir_panel')},
function (result, status) {
if (status === 'OK') {
var center = result.routes[0].bounds.getCenter();
$('#map_canvas').gmap('option', 'center', center);
$('#map_canvas').gmap('refresh')
} else {
alert('Unable to get route');
}
}
);
},
function(){
alert('Unable to get location');
$.mobile.changePage($('#page-home'), { });
},
{ enableHighAccuracy: true } );
Since you want to use geolocation, have you set the sensor to true? Because if you set it false, it won't work.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>

Categories

Resources