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

调用getCurrentPositionAsync报undefined不是函数地图加载失败怎么解决?

问题根因
  • 核心错误是调用了不存在的API:标准navigator.geolocation对象下没有getCurrentPositionAsync方法,你混淆了回调式原生API和第三方库封装的异步Promise API的用法
  • 你将fetchGeoPosition定义为async函数,调用不存在的API抛出的异常没有被捕获,因此触发Unhandled promise rejection报错
  • 额外问题包括:定位函数定义后未执行、缺少异常捕获、变量命名不统一、未做权限二次校验、useFocusEffect缺少清理逻辑
解决方案步骤
  • 第一步:替换正确的定位依赖

React Native 0.60+版本已废弃原生navigator.geolocation,请先安装对应环境的定位包:
非Expo项目执行npm install @react-native-community/geolocation --save,按官方文档配置安卓/ios原生权限
Expo项目执行npx expo install expo-location,使用Expo官方提供的定位API

  • 第二步:修正定位逻辑,补充异常捕获、执行逻辑和清理函数
useFocusEffect( 
  React.useCallback(()=> {
    let isActive = true;
    // 二次校验权限,避免A页面授权后用户手动关闭权限
    const checkPermission = async () => {
      // 替换为你项目中用的权限校验方法,确认位置权限已授予
      const granted = await checkLocationPermission();
      if (!granted) {
        setPositionError('未获得位置权限');
        setIsLoading(false);
        return;
      }
      fetchGeoPosition();
    }

    const fetchGeoPosition = () => {
      // 替换为标准回调式定位API
      navigator.geolocation.getCurrentPosition(
        position => { 
          if (isActive){
            setUserLatitude(position.coords.latitude);
            setUserLongitude(position.coords.longitude);
            setPositionError(null);
            console.log('Location Accessed')
          } 
          setIsLoading(false)
        }, 
        error => {
          if (isActive) {
            setPositionError(error.message);
            setIsLoading(false);
          }
        },
        {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} 
      ); 
    }

    checkPermission().catch(err => {
      if (isActive) {
        setPositionError(err.message);
        setIsLoading(false);
      }
    });

    // 返回清理函数,避免组件卸载后更新已卸载组件的state
    return () => {
      isActive = false;
      navigator.geolocation.clearWatch();
    }
  }, [])
);
  • 第三步:修正地图渲染代码的变量名和参数错误
<View style = {styles.container}>
  {renderLoading()}
  <View style = {styles.header}>
    <MapView
      provider={PROVIDER_GOOGLE}
      style={styles.map}
      // 统一用和state一致的驼峰命名,避免读取undefined
      region= {{
        latitude: userLatitude,
        longitude: userLongitude,
        latitudeDelta: 0.1451,
        longitudeDelta: 0.1451
      }}
    >
    {/* 经纬度有效时才渲染Marker,移除多余的error字段 */}
    {userLatitude && userLongitude && <Marker 
      coordinate={{
        latitude: userLatitude,
        longitude: userLongitude
      }}
    />}
  </MapView>
</View>
  • 第四步:补充兜底逻辑,位置获取失败时可以给默认经纬度加载地图,避免地图直接白屏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:12:03