Ich habe versucht, die GeoLokalisierung von React Native für eine Android-App zu verwenden. Das schlecht dokumentierte Modul finden Sie hier https://facebook.github.io/react-native/docs/geolocation.html ..__ Gemäß der Dokumentation behandeln Sie Standortberechtigungen für Android mit dem folgenden Code in die Datei AndroidManifest.xml
<uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />
Meine Online-Forschung legt jedoch nahe, dass die obige Codezeile für Android-Versionen> = 6.0 unbrauchbar ist
Da meine Implementierung von GeoLocation derzeit nicht funktioniert, habe ich keinen anderen Grund, als zu glauben, dass Standortberechtigungen nicht richtig gehandhabt werden.
Wie kann ich zur Laufzeit erfolgreich eine Standortgenehmigung für die React Native Android App anfordern? Vielen Dank im Voraus!
Das hat bei mir nicht funktioniert
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
}
Ich habe auf https://facebook.github.io/react-native/docs/permissionsandroid.html#request Verwiesen und check () einen boolean zurückgegeben
const granted = await PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION );
if (granted) {
console.log( "You can use the ACCESS_FINE_LOCATION" )
}
else {
console.log( "ACCESS_FINE_LOCATION permission denied" )
}
Ich habe es gelöst, indem ich die targetSdkVersion (in meinem Fall 23 in compileSdkVersion) in Android/app/build.gradle geändert habe.
Bearbeiten Sie AndroidManifest.xml in Android/src/main und fügen Sie das hinzu
<uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION"/>
//Nächster :
import { PermissionsAndroid } from 'react-native';
// und füge diese Methode hinzu:
export async function requestLocationPermission()
{
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Example App',
'message': 'Example App access to your location '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location")
alert("You can use the location");
} else {
console.log("location permission denied")
alert("Location permission denied");
}
} catch (err) {
console.warn(err)
}
}
// und greifen Sie auf die Methode zu, wenn Sie zur Laufzeit den Speicherort anfordern
async componentWillMount() {
await requestLocationPermission()
}
Sie können den reagierten nativen PermissionsAndroid verwenden, um die Berechtigung anzufordern: https://facebook.github.io/react-native/docs/permissionsandroid.html#request
Eine einfachere Option ist die Verwendung einer Bibliothek, die dies für Sie erledigt, z. B. https://github.com/yonahforst/react-native-permissions
Hier ist mein Code, um den aktuellen Standort in Android und IOS mit Erlaubnis zu finden
Für Android :
Sie müssen die folgende Berechtigung in der Android-Datei AndroidManifest.xml .__ hinzufügen.
Für IOS Sie müssen den Schlüssel NSLocationWhenInUseUsageDescription in Info.plist einschließen, um die Geolocation bei der Verwendung der App zu aktivieren. Die Geolokalisierung ist standardmäßig aktiviert, wenn Sie ein Projekt mit "Reactative Init" erstellen.
Hier finden Sie den Code zum Ermitteln des aktuellen Standorts (Breitengrad und Längengrad):
//This is an example code to get Geolocation//
import React from 'react';
//import react in our code.
import {View, Text, StyleSheet, Image ,PermissionsAndroid,Platform} from 'react-native';
//import all the components we are going to use.
export default class App extends React.Component {
state = {
currentLongitude: 'unknown',//Initial Longitude
currentLatitude: 'unknown',//Initial Latitude
}
componentDidMount = () => {
var that =this;
//Checking for the permission just after component loaded
if(Platform.OS === 'ios'){
this.callLocation(that);
}else{
async function requestCameraPermission() {
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) {
//To Check, If Permission is granted
that.callLocation(that);
} else {
alert("Permission Denied");
}
} catch (err) {
alert("err",err);
console.warn(err)
}
}
requestCameraPermission();
}
}
callLocation(that){
//alert("callLocation Called");
navigator.geolocation.getCurrentPosition(
//Will give you the current location
(position) => {
const currentLongitude = JSON.stringify(position.coords.longitude);
//getting the Longitude from the location json
const currentLatitude = JSON.stringify(position.coords.latitude);
//getting the Latitude from the location json
that.setState({ currentLongitude:currentLongitude });
//Setting state Longitude to re re-render the Longitude Text
that.setState({ currentLatitude:currentLatitude });
//Setting state Latitude to re re-render the Longitude Text
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
that.watchID = navigator.geolocation.watchPosition((position) => {
//Will give you the location on location change
console.log(position);
const currentLongitude = JSON.stringify(position.coords.longitude);
//getting the Longitude from the location json
const currentLatitude = JSON.stringify(position.coords.latitude);
//getting the Latitude from the location json
that.setState({ currentLongitude:currentLongitude });
//Setting state Longitude to re re-render the Longitude Text
that.setState({ currentLatitude:currentLatitude });
//Setting state Latitude to re re-render the Longitude Text
});
}
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID);
}
render() {
return (
<View style = {styles.container}>
<Image
source={{uri:'https://png.icons8.com/dusk/100/000000/compass.png'}}
style={{width: 100, height: 100}}
/>
<Text style = {styles.boldText}>
You are Here
</Text>
<Text style={{justifyContent:'center',alignItems: 'center',marginTop:16}}>
Longitude: {this.state.currentLongitude}
</Text>
<Text style={{justifyContent:'center',alignItems: 'center',marginTop:16}}>
Latitude: {this.state.currentLatitude}
</Text>
</View>
)
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
justifyContent:'center',
marginTop: 50,
padding:16,
backgroundColor:'white'
},
boldText: {
fontSize: 30,
color: 'red',
}
})
Sie können die Standortgenehmigung mit folgendem Code anfordern
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You can use the location")
} else {
alert("Location permission denied")
}
} catch (err) {
console.warn(err)
}
alert('hi');
Ich habe zwei Dinge bemerkt:
compileSdkVersion 23
in der build.gradle
-Datei ändernBeispielcode:
import React, { Component } from 'react';
import { Text, PermissionsAndroid, Alert } from 'react-native';
export default class RuntimePermissionSample extends React.Component {
constructor(props) {
super(props);
}
async requestLocationPermission() {
const chckLocationPermission = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
if (chckLocationPermission === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Cool Location App required Location permission',
'message': 'We required Location permission in order to get device location ' +
'Please grant us.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
alert("You don't have access for the location");
}
} catch (err) {
alert(err)
}
}
};
render() {
return (
<Text
onPress={() => this.requestLocationPermission()}>
Request Location Permission
</Text>
)
}
}
Hoffe das würde dir helfen.
Das hat bei mir funktioniert
async requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.props.navigation.navigate("MapScreen")
} else {
alert("Camera permission denied")
}
} catch (err) {
console.warn(err)
}
}