React Native:无法使用地理位置API访问位置

时间:2018-06-20 12:34:05

标签: react-native geolocation

Not actual screenshot of the code. But error is same 错误:似乎该应用没有访问位置的权限。将以下行添加到您应用的AndroidManifest.xml

即使我已在manifest.xml中添加了权限并要求运行时权限,我也无法访问GPS。

我的AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.location">

<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" />
.....
.....

完整代码:

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

export default class App extends Component {
  async requestLocationPermission() {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
          'title': 'Location Access Permission',
          'message': 'Expensify would like to use your location ' +
                     'so you we track you.'
        }
      )
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        console.log("You can use the location")
      } else {
        console.log("Location permission denied")
      }
    } catch (err) {
      console.warn(err)
    }
  }
  componentDidMount() {
    console.log("compdidmount");
    this.requestLocationPermission();
//Crashes here on getCurrentPosition
        navigator.geolocation.getCurrentPosition(
          (position) => {
            console.log(position.coords.latitude);
           },
           (error) => {
            console.log(error)
          },
          {enableHighAccuracy: true, timeout: 20000, maximumAge: 10000}
        );
    }
      render() {
        return (
          <View style>
            <Text style>
              Tracking App
            </Text>
          </View>
        );
      }
    }

2 个答案:

答案 0 :(得分:0)

我在CameraRoll上遇到了同样的问题。我已解决该问题,以在应用启动时征求许可。您应该使用此:

import { PermissionsAndroid } from 'react-native';

async function requestCameraPermission() {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      {
        'title': 'Location Permission',
        'message': 'Location Permission' +
                   'so you can use GPS location.'
      }
    )
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("You can use GPS")
    } else {
      console.log("GPS location denied")
    }
  } catch (err) {
    console.warn(err)
  }
}

答案 1 :(得分:0)

我通过删除并重新安装该应用程序解决了这个问题。