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

React Native MapView initialRegion经纬度传值报NaN如何解决

报错根因
  • 经纬度状态初始值设为字符串"Loading...",组件首次渲染时执行Number("Loading...")会直接返回NaN,触发类型校验报错。
  • 定位逻辑中拿到latitude、longitude结果后,没有调用状态更新方法把经纬度存下来,状态始终停留在初始的"Loading..."。
  • react-native-maps的initialRegion属性仅在MapView组件首次挂载时读取一次,异步拿到定位结果后再更新状态,不会触发initialRegion的重新赋值。
  • 额外说明:expo-location返回的经纬度本身就是数值类型,不需要额外做类型转换,之前的NaN问题和定位返回值类型无关。
修复方案
  1. 调整状态定义,把经纬度初始值设为null,补上缺失的经度状态,移除没用的冗余状态:
// 替换原有的la、location状态定义
const [latitude, setLatitude] = useState(null);
const [longitude, setLongitude] = useState(null);
  1. 在定位请求逻辑中,拿到经纬度后同步更新状态,同时补上权限拒绝后的逻辑终止判断,避免无权限时继续执行定位逻辑报错:
const ask = async () => {
  const { granted } = await Location.requestForegroundPermissionsAsync();
  if (!granted) {
    setOk(false);
    return;
  }
  const {
    coords: { latitude, longitude },
  } = await Location.getCurrentPositionAsync({ accuracy: 5 });
  // 补上之前遗漏的经纬度状态赋值
  setLatitude(latitude);
  setLongitude(longitude);

  const location = await Location.reverseGeocodeAsync(
    { latitude, longitude },
    { useGoogleMaps: false }
  );
  setCity(location[0].district)
};
  1. 增加条件渲染:经纬度加载完成前不挂载MapView组件,从根源上避免传入无效值。等经纬度拿到后再渲染MapView,此时传入的initialRegion就是正确的定位值:
return (
  <>
    <View style={{flex:0.16,backgroundColor:'white'}}>
      <Text style={{fontSize:40,marginTop:55,marginLeft:30}}>{city}</Text>
      {!ok && <Text style={{marginLeft:30, color:'red'}}>请开启定位权限</Text>}
    </View>
    
    <View style={{ flex: 1 }}>
      {!latitude || !longitude ? (
        <View style={{flex:1, alignItems:'center', justifyContent:'center'}}>
          <Text>定位加载中...</Text>
        </View>
      ) : (
        <MapView
          style={{ flex: 1 }}
          provider={PROVIDER_GOOGLE}
          initialRegion={{
            latitude,
            longitude,
            latitudeDelta: 0.00922,
            longitudeDelta: 0.00321,
          }}
        />
      )}
    </View>
    <StatusBar style="black" />
  </>
);

补充提示:如果后续需要动态切换地图显示的区域,不要修改initialRegion属性,换成给MapView绑定region属性关联经纬度状态即可,initialRegion只做组件初始化使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 00:54:28