地图加载时因经纬度未就绪崩溃,求等待经纬度加载的解决方案
解决方案
1. 修正经纬度变量的类型错误
你当前用contratadosPor.map(...)得到的latitude/longitude是数组,但地图组件需要的是单个经纬度数值。如果contratadosPor只会返回单个匹配对象,直接取第一个元素的lat/lng即可:
const contratadosPor = paseadores.filter(({ contratadoPor }) => contratadoPor === id); // 取第一个匹配条目,而非返回数组 const targetPaseador = contratadosPor.length > 0 ? contratadosPor[0] : null; const latitude = targetPaseador?.lat; const longitude = targetPaseador?.lng;
2. 避免地图初始化传入null值
MapContainer的center属性不接受null,要么设置一个兜底的默认坐标,要么条件渲染地图组件,等经纬度加载完成后再渲染:
// 判断是否有有效经纬度 const hasValidPosition = latitude !== undefined && longitude !== undefined;
在return中添加条件渲染:
{hasValidPosition ? ( <MapContainer center={[latitude, longitude]} zoom={16}> {/* 地图子组件 */} </MapContainer> ) : ( <div>加载位置中...</div> // 加载状态提示 )}
3. 修复异步ID的依赖问题
初始时isAuthenticated为false,id是空字符串,导致第一次dispatch(getpaseadores())用空ID过滤不到数据。需将id加入useEffect依赖数组,确保ID有效后再发起请求:
useEffect(() => { if (id) { // 仅当ID存在时请求数据 dispatch(getDetalleUsuario(id)); dispatch(getusers()); dispatch(getpaseadores()); } }, [id, dispatch]); // 加入id依赖
4. 修正FlyMapTo组件逻辑
map.flyTo需传入包含center的配置对象,而非直接传数组- 监听position变化,将其加入useEffect依赖数组
- 移除错误的
enableHighAccuracy参数(这是地理定位API选项,不属于useEffect依赖):
function FlyMapTo({ position }) { const map = useMap(); useEffect(() => { if (position) { map.flyTo({ center: position, zoom: 16, duration: 1000 // 可选:设置动画时长 }); } }, [map, position]); // 监听position变化 return null; }
在MapContainer中传入position props:
<FlyMapTo position={position} />
完整修改后的代码
export default function GeolocationMap() { const paseadores = useSelector((state) => state.paseadores); const dispatch = useDispatch(); const { user, isAuthenticated } = useAuth0(); let id = ""; if (isAuthenticated) { id = user.sub.substring(6); } // 仅当ID有效时请求数据 useEffect(() => { if (id) { dispatch(getDetalleUsuario(id)); dispatch(getusers()); dispatch(getpaseadores()); } }, [id, dispatch]); // 定时刷新paseadores数据,确保ID存在才执行 useEffect(() => { const interval = setInterval(() => { if (id) { dispatch(getpaseadores()); } }, 1500); return () => clearInterval(interval); }, [id, dispatch]); // 过滤并取第一个匹配的paseador const contratadosPor = paseadores.filter(({ contratadoPor }) => contratadoPor === id); const targetPaseador = contratadosPor.length > 0 ? contratadosPor[0] : null; const latitude = targetPaseador?.lat; const longitude = targetPaseador?.lng; const hasValidPosition = latitude !== undefined && longitude !== undefined; const position = hasValidPosition ? [latitude, longitude] : null; console.log("latlng", latitude, longitude); function FlyMapTo({ position }) { const map = useMap(); useEffect(() => { if (position) { map.flyTo({ center: position, zoom: 16, duration: 1000 }); } }, [map, position]); return null; } return ( <div className={stl.paginaGps}> <NavBar /> <div className={stl.titulo}>Aqui podras ver la ubicacion del paseador en tiempo real</div> <div className={stl.paseador}> {/* 条件渲染地图,避免传入无效center值 */} {hasValidPosition ? ( <MapContainer center={position} zoom={16}> <FlyMapTo position={position} /> <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' /> <Marker position={position} icon={IconLocationWalker}> <Popup>El Paseador se encuentra Aqui</Popup> </Marker> </MapContainer> ) : ( <div>正在加载位置信息...</div> )} </div> <Footer /> </div> ); }
内容的提问来源于stack exchange,提问作者Andres Cantlon
相关产品推荐
相关产品推荐

