React Native Undefined不是对象 - Geolocation

时间:2018-04-13 10:15:01

标签: react-native

我正在使用Windows 10并且正在运行Android 7.0设备。

当用户按下按钮时,我试图让设备使用地理定位显示其长度和当前位置。

我创建了一个按钮,当用户点击它时会显示一条警告消息 - 到目前为止一直很好。

然后我尝试添加获取当前位置,然后我的应用程序崩溃并出现错误:

  

undefined不是一个对象(评估   ' _reactNative.Geolocation.getCurrentPosition&#39)

这是我的代码:

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

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>

        <Button
          onPress={() => {
            var loc = Geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]);
            Alert.alert(loc);

            //Alert.alert('You tapped the button!');
          }}
          title="Display GPS"
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

&#34; undefined不是一个对象&#34;意思是,我该如何解决? (当我试图访问相机时,我之前遇到了同样的错误。)

2 个答案:

答案 0 :(得分:5)

React-Native(v 0.55)Geolocation文档说,

  

作为浏览器polyfill,此API可通过   navigator.geolocation global - 您不需要导入它。

不要从Geolocation导入react-native。而是直接使用navigator.geolocation作为全局对象。

例如,

navigator.geolocation.getCurrentPosition(
  (position) => console.log(position),
  (err) => console.log(err),
  { enableHighAccuracy: false, timeout: 8000, maximumAge: 10000 }
);

答案 1 :(得分:2)

先前的答案不再准确。该库已从本机核心移至其社区回购。

https://stackoverflow.com/a/56909007/4458849

相关问题