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

React Native Maps Android端newLatLngBounds报错地图尺寸为0 iOS运行正常

问题原因

该错误仅在Android端触发是因为Android原生Google地图组件要求必须在自身布局渲染完成、尺寸不为0之后,才能执行区域设置、边界适配操作,iOS系统对这类异常操作做了内置容错,因此没有报错。

基于Hooks的修改方案

1. 新增依赖导入和状态声明

首先补全缺失的导入,新增地图引用和就绪状态:

import React, { useState, useEffect, useRef } from "react";
// 你原有代码中使用了Constants但未导入,需补上
import Constants from 'expo-constants';

function Locator({navigation, route}) { 
  // 原有状态保留,新增以下两项
  const mapRef = useRef(null);
  const [mapReady, setMapReady] = useState(false);
  // 原有状态不变
  const [user_latitude, setUserLatitude] = useState(0)
  const [user_longitude, setUserLongitude] = useState(0)
  // ...其余原有代码

2. 修改MapView组件配置

移除直接绑定的region属性,新增地图就绪回调:

<MapView
  ref={mapRef}
  provider={PROVIDER_GOOGLE}
  style={styles.map}
  onMapReady={() => setMapReady(true)}
>
  <Marker 
    coordinate={{
      latitude: user_latitude,
      longitude: user_longitude,
      error: position_error,
    }}
  />
</MapView>

3. 新增监听逻辑,延迟设置地图区域

新增useEffect,等用户坐标获取完成、且地图渲染就绪后再设置显示区域:

// 放在现有useEffect、useFocusEffect之后即可
useEffect(() => {
  // 过滤初始坐标和地图未就绪的状态
  if (user_latitude !== 0 && user_longitude !== 0 && mapReady && mapRef.current) {
    mapRef.current.animateToRegion({
      latitude: user_latitude,
      longitude: user_longitude,
      latitudeDelta: 0.1451,
      longitudeDelta: 0.1451
    }, 100)
  }
}, [user_latitude, user_longitude, mapReady])

4. 可选兼容方案(适配边界场景)

如果后续需要调用newLatLngBounds适配多个坐标点的显示边界,Android端主动传入地图尺寸即可避免报错:

if (Platform.OS === 'android' && mapRef.current) {
  // 直接使用你已经获取的屏幕宽高作为地图尺寸
  mapRef.current.newLatLngBounds(你的边界对象, width, height, 50)
} else {
  mapRef.current.fitToCoordinates(你的坐标数组, {
    edgePadding: {top:50, right:50, bottom:50, left:50}
  })
}

其他注意事项

你的原有代码中permission_get方法调用了未声明的setErrorMsg,需补充const [errorMsg, setErrorMsg] = useState(null)状态声明,避免额外报错。


内容的提问来源于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.06 09:51:01