React-Native-Maps获取当前位置

3
我想显示我的当前位置,但是我无法做到。
我在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
    }
});

这是我的React Native版本。 "dependencies": { "react": "16.9.0", "react-native": "0.61.5", "react-native-android-location-enabler": "^1.2.0", "react-native-geolocation-service": "^3.1.0", "react-native-maps": "0.26.1" - Contractor
谷歌地图运行良好。然而模拟器上的地图没有显示我的当前位置。因此,我更改了我的代码以确认我的位置。 - Contractor
在 React Native 的 0.60.0 版本及以上中,navigator.geolocation.getCurrentPosition 方法已经无法使用,请使用 https://www.npmjs.com/package/@react-native-community/geolocation。 - Vishal Dhanotiya
我也尝试使用@react-native-community/geolocation库。然而,我的控制台仍然显示谷歌总部的坐标。亲爱的Dhanotiya,请您能详细解释一下吗? - Contractor
请检查以下网址 https://dev59.com/tXE95IYBdhLWcg3whOLK#45098850 - Vishal Dhanotiya
显示剩余2条评论
1个回答

2
我使用下面的代码解决了这些问题。
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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接