TypeError:undefined 不是 react-native-google-places-autocomplete 中的对象(评估 'navigator.geolocation.getCurrentPosition')

kes*_*ava 5 react-native google-places-autocomplete

我正在尝试将react-native-google-places-autocomplete用于谷歌地点,同时我想要用户当前的位置。

但我收到一个错误,称为

类型错误:未定义不是对象(评估 'navigator.geolocation.getCurrentPosition')

我已经通过网络搜索解决方案,每个人都说navigator.geolocation.getCurrentPosition工作正常。

但不知道为什么它对我不起作用..

这是我的代码

componentDidMount() {
navigator.geolocation.getCurrentPosition(
  position => {
    const initialPosition = JSON.stringify(position);
    let region = {
        latitude: position.coords.latitude,
        longitude: position.coords.longitude,
        latitudeDelta: 0.0922,
        longitudeDelta: 0.0421,
        }
    this.setState({initialPosition:region});
    console.log("lat "+position.coords.latitude+" longi "+position.coords.longitude)
    console.log("initialPosition")
    console.log(this.state.initialPosition)
  },
   error => console.log("Error "+ JSON.stringify(error)),
  {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000},
);
this.watchID = Geolocation.watchPosition(position => {
  const lastPosition = JSON.stringify(position);
  this.setState({lastPosition});
});
Run Code Online (Sandbox Code Playgroud)

}

kes*_*ava 11

我已经通过@react-native-community/geolocation并在这里找到了解决方案。我已经完成了以下步骤。1.通过安装@react-native-community/geolocation

npm install @react-native-community/geolocation --save
Run Code Online (Sandbox Code Playgroud)
  1. 在 react-native-google-places-autocomplete 的侧节点模块中的 GooglePlacesAutocompleteExample.js 文件中的类上方添加以下行

    navigator.geolocation = require('@react-native-community/geolocation'); 完成它的工作..


zac*_*hee 9

  1. npm install @react-native-community/geolocation --save
  2. import Geolocation from '@react-native-community/geolocation';
  3. 而不是navigator.geolocation.getCurrentPosition使用Geolocation.getCurrentPosition

  • 这似乎是已接受的答案已经说明的内容。不应发布重复的答案。 (2认同)