【问题标题】:navigator.geolocation.watchPosition not working correctly on ios devicenavigator.geolocation.watchPosition 在 ios 设备上无法正常工作
【发布时间】:2017-11-04 09:51:25
【问题描述】:

我有一个奇怪的行为,找不到解决办法。在我的 React Native 应用程序中,我使用 navigator.geolocation 来确定当前位置。我的应用程序与 Facebook 的地理位置代码中的示例几乎相同。

在模拟器中,我的应用程序运行良好,但是当我将它部署到我的 iphone 时,返回位置(通过 getCurrentPosition 和 watchPosition)不正确。例如速度和航向是-1,精度是65。经度和纬度似乎是有效的,但不是我的真实位置(在另一个国家)。 不管我是通过调试还是发布到 iphone 来部署应用程序,它的反应总是一样的。

但是,如果我启动 TomTom 并将这个应用程序放在后台,然后启动我的 GeolocationExample 应用程序,一切都会正常运行。

我创建的应用程序如下:

react-native init GeolocationExample

然后我用这段代码替换了文件 index.ios.js。

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

export default class GeolocationExample extends React.Component {
  state = {
    initialPosition: 'unknown',
    lastPosition: 'unknown',
  };

  watchID: ?number = null;

  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        var initialPosition = JSON.stringify(position);
        this.setState({initialPosition});
      },
      (error) => alert(JSON.stringify(error)),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
      var lastPosition = JSON.stringify(position);
      this.setState({lastPosition});
    });
  }

  componentWillUnmount() {
    navigator.geolocation.clearWatch(this.watchID);
  }

  render() {
    return (
      <View style={styles.main}>
        <Text>
          <Text style={styles.title}>Initial position: </Text>
          {this.state.initialPosition}
        </Text>
        <Text>
          <Text style={styles.title}>Current position: </Text>
          {this.state.lastPosition}
        </Text>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  main: {
    margin: 30
  },
  title: {
    fontWeight: '500',
  },
});

AppRegistry.registerComponent('GeolocationExample', () => GeolocationExample);

【问题讨论】:

  • @Tim 感谢您的更正
  • 这个有什么完美的吗?

标签: ios react-native geolocation


【解决方案1】:

第一个选项:添加参数

{enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, accuracy:10 //ten meters not in the document}

第二个选项:设置第 28 行

#define RCT_DEFAULT_LOCATION_ACCURACY kCLLocationAccuracyBest //default was kCLLocationAccuracyHundredMeters 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2019-02-04
    相关资源
    最近更新 更多