react-native - 类型错误 : undefined is not an object (evaluating 'navigator.geolocation.requestAuthorization' )

标签 react-native geolocation

我正在尝试调用:

`navigator.geolocation.requestAuthorization();`

请求地理定位许可。

但是,这会导致在 iOS 模拟器中运行时出错

这在某一时刻起作用,但停止了。我试图删除并创建一个新项目。我还尝试卸载/重新安装节点和 react-native-cli。
import React, {Fragment, Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

export default class App extends Component {

    constructor(props)
    {
        super(props);

        navigator.geolocation.requestAuthorization();
    }

    render() {

        return (

                <View style={styles.MainContainer}>
                <SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
                <Text style={styles.sectionTitle}>Hello World!</Text>
                </SafeAreaView>
                </View>

                );
    }
}

const styles = StyleSheet.create({
  MainContainer :{
     justifyContent: 'center',
     flex:1,
     margin: 5,
     marginTop: (Platform.OS === 'ios') ? 20 : 0,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
});

我收到此错误:
[error][tid:com.facebook.react.JavaScript] TypeError: undefined is not an object (evaluating 'navigator.geolocation.requestAuthorization')

This error is located at:
    in App (at renderApplication.js:40)
    in RCTView (at View.js:35)
    in View (at AppContainer.js:98)
    in RCTView (at View.js:35)
    in View (at AppContainer.js:115)
    in AppContainer (at renderApplication.js:39)

最佳答案

地理定位已从 react native .60 版本中提取。如果您需要替代解决方案

安装 react-native-community/geolocation

npm install @react-native-community/geolocation --save


react-native link @react-native-community/geolocation

然后

IOS

您需要包含 NSLocationWhenInUseUsageDescription键入 Info.plist使用应用程序时启用地理定位。
为了在后台启用地理定位,您需要在 Info.plist 中包含“NSLocationAlwaysUsageDescription”键,并在 Xcode 的“功能”选项卡中添加位置作为背景模式。

安卓

要请求访问位置,您需要将以下行添加到您的应用程序的 AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

用法
import Geolocation from '@react-native-community/geolocation';

Geolocation.getCurrentPosition(info => console.log(info));

关于react-native - 类型错误 : undefined is not an object (evaluating 'navigator.geolocation.requestAuthorization' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56908771/

相关文章:

javascript - 从谷歌地点获取附近的位置并从结果中在谷歌地图上添加标记

android - React Native PanResponder 限制X位置

react-native - 如何使用expo-sqlite通过typescript执行sql?

xcode - 未找到 RCT 链接管理器文件

ios - React-Native:无法触发 native UIButton 触摸事件

reactjs - 如果应用程序关闭,则 React-Native 深层链接不起作用(React-Navigation v5)

c# - 指定操作区域并验证位置是否在该区域内

java - 从一个坐标到另一个坐标的方位

angularjs - 如何通过在 angularjs 中使用地理定位 api 获取邮政编码或邮政编码

android - Osmdroid 最大缩放级别显示两个地理位置