react-native-maps获取当前位置

时间:2019-12-23 23:23:14

标签: android react-native permissions location react-native-maps

我想显示我的当前位置,但不能。

我向AndroidManifest.xml添加权限代码,如下所示。

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

但是,我的模拟器没有询问我“使用该应用程序时允许00访问您的位置”。

下面是我的app.js代码。

import React, { Component } from 'react';
import { Alert, StyleSheet, Text, View, TouchableOpacity, PermissionsAndroid } from 'react-native';

export default class App extends Component {
    state = {
        location: null
    };

    findCoordinates = () => {
        navigator.geolocation.getCurrentPosition(
            position => {
                const location = JSON.stringify(position);

                this.setState({ location });
            },
            error => Alert.alert(error.message),
            { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
        );
    };

    render() {
        return (
            <View style={styles.container}>
                <TouchableOpacity onPress={this.findCoordinates}>
                    <Text style={styles.welcome}>Find My Coords?</Text>
                    <Text>Location: {this.state.location}</Text>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10
    }
});

1 个答案:

答案 0 :(得分:0)

我使用下面的代码解决了问题。

async function requestGeolocationPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'Ridesharer Geolocation Permission',
        'message': 'Ridesharer needs access to your current location so you can share or search for a ride'
      });
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use the geolocation")
    } else {
      console.log("Geolocation permission denied")
    }
  } catch (err) {
    console.warn(err)
  }
}
requestGeolocationPermission();