You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native定位追踪报错:undefined is not an object (evaluating 'navigator.geolocation.clearWatch')

解决React Native定位追踪中的navigator.geolocation.clearWatch未定义错误

这个错误的核心原因是全局的navigator.geolocation在新版本React Native中已被移除或不再默认支持,官方现在推荐使用专用的定位库来实现相关功能。以下是具体解决步骤:

1. 安装并引入正确的定位库

如果你的React Native版本在0.60及以上,需要安装社区维护的定位库:

npm install @react-native-community/geolocation --save
# 或者用yarn
yarn add @react-native-community/geolocation

安装完成后,在你的组件文件顶部导入该库:

import Geolocation from '@react-native-community/geolocation';
import { Platform } from 'react-native';

2. 修改你的watchLocation方法

将代码中所有的navigator.geolocation替换为导入的Geolocation对象,修改后的代码如下:

watchLocation = () => {
  const { coordinate } = this.state;

  this.watchID = Geolocation.watchPosition(
    position => {
      const { latitude, longitude } = position.coords;

      const newCoordinate = {
        latitude,
        longitude,
      };

      if (Platform.OS === 'android') {
        if (this.marker) {
          this.marker._component.animateMarkerToCoordinate(newCoordinate, 500);
        }
      } else {
        coordinate.timing(newCoordinate).start();
      }

      this.setState({
        latitude,
        longitude,
      });
    },
    error => console.log(error),
    {
      enableHighAccuracy: true,
      timeout: 20000,
      maximumAge: 1000,
      distanceFilter: 30,
    }
  );
};

当你需要停止定位追踪时,也要用Geolocation.clearWatch:

stopWatching = () => {
  if (this.watchID) {
    Geolocation.clearWatch(this.watchID);
    this.watchID = null;
  }
};

3. 配置平台权限

  • Android:在android/app/src/main/AndroidManifest.xml中添加定位权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  • iOS:在ios/[你的项目名]/Info.plist中添加权限描述:
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要获取你的位置信息来进行定位追踪</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>需要获取你的位置信息来进行定位追踪</string>

额外说明

如果你是使用Expo开发的项目,建议直接使用expo-location库,用法类似,只需替换导入和API调用即可。

内容的提问来源于stack exchange,提问作者ab_404

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 10:25:33