反应原生GeoLocation null引用错误

时间:2018-04-12 15:11:44

标签: react-native geolocation

我使用以下代码尝试获取当前位置:

componentDidMount() {
    this.watchID = navigator.geolocation.watchPosition((position) => {
        let region = {
            latitude:       position.coords.latitude,
            longitude:      position.coords.longitude,
            latitudeDelta:  0.00922*1.5,
            longitudeDelta: 0.00421*1.5,
            enableHighAccuracy: true
        }
        this.onRegionChange(region, region.latitude, region.longitude);
    });
}

我得到了:

Attempt to invoke interface method 'boolean abi26_0_0.com.facebook.react.bridge.ReadableMap.hasKey(java.lang.String)' on a null object reference

这就是触发这条线:

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

我可能需要输入一些东西吗?我无法在网上找到任何相关信息。谢谢!

1 个答案:

答案 0 :(得分:3)

经过几个小时的搜索,我终于把它钉了起来。

如果您正在使用CRNA,就像我一样(create-react-native-app就是您构建应用程序的方式),您需要完成函数调用的所有部分。这些是(成功,错误,选项)。下面的代码是如何实现所有这些部分并删除此错误。

componentDidMount() {
this.watchId = navigator.geolocation.watchPosition(
  (position) => {
    this.setState({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude,
      error: null,
    });
  },
  (error) => this.setState({ error: error.message }),
  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },
);
}