diff --git a/MapView/index.tsx b/MapView/index.tsx index b0221097b398a25bb2034084292e22597a3afcca..9fc8b1e7a1d89b9ea3170ce85ee4d2116b87b8c5 100644 --- a/MapView/index.tsx +++ b/MapView/index.tsx @@ -3,10 +3,11 @@ import { useBoolean, useEventEmitter, useUpdate } from 'ahooks'; import React, { createContext, forwardRef, + memo, useEffect, useImperativeHandle, - useLayoutEffect, useRef, + useState, } from 'react'; import mapEnv from '../mapEnv'; import styles from './index.less'; @@ -40,6 +41,8 @@ const MapView: React.ForwardRefRenderFunction< } = props; const mapRef = useRef(null); + /** 地图容器尺寸 */ + const [mapSize, setMapSize] = useState<{ width?: number; height?: number }>(); /** 地图实例 */ const mapViewer = useRef(null); const update = useUpdate(); @@ -55,6 +58,7 @@ const MapView: React.ForwardRefRenderFunction< // mapViewer.current = null; }; }, [isReady]); + /** * @description 暴露给父组件的地图实例 */ @@ -62,6 +66,9 @@ const MapView: React.ForwardRefRenderFunction< /** 地图初始化 */ const initMap = () => { + if (!mapRef.current) { + return; + } if (!center) { throw new Error('地图中心点是必须的'); } @@ -138,43 +145,24 @@ const MapView: React.ForwardRefRenderFunction< }); }; - useLayoutEffect(() => { - initMap(); - }, []); + useEffect(() => { + console.log(1111); + const { width, height } = + mapRef.current?.parentElement?.getBoundingClientRect() as DOMRect; + setMapSize({ width, height }); + }, [mapRef]); + useEffect(() => { + /** 已重新计算容器宽高后,初始化地图 */ + if (mapSize?.width && mapSize?.height) { + initMap(); + } + }, [mapSize]); /** 地图层级放大 */ const zoomIn = () => { mapViewer.current?.camera.zoom(0.5); }; - // /** 设置地图视野,显示所有覆盖物 */ - // const setViewport = () => { - // if (boundingSpherePoints) { - // /** 设置高程 */ - // let z = center.z ?? 200000; - // /**根据缩放等级,更新 z 值 */ - // if (zoom && zoom < 20 && zoom > 0) { - // z = 20000 * zoom; - // } - // const info = calculateBoundingCircle(boundingSpherePoints); - // mapViewer.current?.camera.flyToBoundingSphere( - // { - // x: info.center[0], - // y: info.center[1], - // z: z, - // }, - // info.radius, - // { - // offset: { - // heading: 6.283054179776913, - // pitch: -Math.PI / 2, - // roll: 0, - // }, - // }, - // ); - // } - // }; - /** 地图层级缩小 */ const zoomOut = () => { mapViewer.current?.camera.zoom(2); @@ -203,7 +191,12 @@ const MapView: React.ForwardRefRenderFunction< return (
-
+
{isReady && children} {showCustomComponent && (
@@ -224,4 +217,4 @@ const MapView: React.ForwardRefRenderFunction< ); }; -export default forwardRef(MapView); +export default memo(forwardRef(MapView));