TypeError: undefined is not an object( evaluating 'navigator.geolocation.getCurrentPosition')

TypeError: undefined is not an object( evaluating 'navigator.geolocation.getCurrentPosition')

我最近开始研究 react-native,现在正尝试访问 react-native-maps,因为无论我在地图上单击什么地方,它都应该给我坐标。我安装了 react-native-map 并尝试使用下面的方法

navigator.geolocation.getCurrentPosition((position) => {

我遇到了以下错误。

E | ReactNativeJS ▶︎ TypeError: undefined is not an object (evaluating 'navigator.geolocation.getCurrentPosition')
                             │ 
                             │ 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)

我的代码看起来像这样。

  componentDidMount() {
    navigator.geolocation.getCurrentPosition((position) => {
      var lat = parseFloat(position.coords.latitude)
      var long = parseFloat(position.coords.longitude)

      var initialRegion = {
        latitude: lat,
        longitude: long,
        latitudeDelta: LATITUDE_DELTA,
        longitudeDelta: LONGITUDE_DELTA,
      }

      this.setState({initialPosition: initialRegion})
    },
    (error) => alert(JSON.stringify(error)),
    {enableHighAccuracy: true, timeout: 20000});
  }

我也尝试了一些其他的方法,比如

this.watchID = navigator.geolocation.watchPosition((position) => {

navigator.geolocation.clearWatch(this.watchID);

如何解决这个问题并使这些方法在 react-native-maps 中起作用

我正在使用 import MapView from 'react-native-maps'; 这个导入

我不确定这是否是您正在寻找的答案,但如果您在使用 react-native-community, you can easily follow its great example 中的这个 react-native-geolocation 库时没有任何问题。请不要忘记像这样在 AndroidManifest.xml 文件中添加权限 -

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

您还需要在清单文件中添加元数据 -

 <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_API_KEY"/>

您可以使用 Google API 控制台轻松生成 API 密钥