components_amap.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import React, { useEffect, useRef } from 'react';
  2. import { useQuery, useQueryClient } from '@tanstack/react-query';
  3. import { getGlobalConfig } from './utils.ts';
  4. import type { GlobalConfig } from '../share/types.ts';
  5. import { Spin } from 'antd';
  6. import './style_amap.css';
  7. import { MapMode, MarkerData } from '../share/types.ts';
  8. // 在线地图配置
  9. export const AMAP_ONLINE_CONFIG = {
  10. // 高德地图 Web API 密钥
  11. API_KEY: getGlobalConfig('MAP_CONFIG')?.KEY || '',
  12. // 主JS文件路径
  13. MAIN_JS: 'https://webapi.amap.com/maps?v=2.0&key=' + (getGlobalConfig('MAP_CONFIG')?.KEY || ''),
  14. // 插件列表
  15. PLUGINS: ['AMap.MouseTool', 'AMap.RangingTool', 'AMap.Scale', 'AMap.ToolBar', 'AMap.MarkerCluster'],
  16. };
  17. export const AMAP_OFFLINE_CONFIG = {
  18. // 主JS文件路径
  19. MAIN_JS: '/amap/amap3.js?v=2.0',
  20. // 插件目录
  21. PLUGINS_PATH: '/amap/plugins',
  22. // 插件列表
  23. PLUGINS: ['AMap.MouseTool', 'AMap.RangingTool', 'AMap.Scale', 'AMap.ToolBar', 'AMap.MarkerCluster'],
  24. };
  25. // 离线瓦片配置
  26. export const TILE_CONFIG = {
  27. // 瓦片地图基础路径
  28. BASE_URL: '/amap/tiles',
  29. // 缩放级别范围
  30. ZOOMS: [3, 20] as [number, number],
  31. // 默认中心点
  32. DEFAULT_CENTER: [108.25910334, 27.94292459] as [number, number],
  33. // 默认缩放级别
  34. DEFAULT_ZOOM: 15
  35. } as const;
  36. // 地图控件配置
  37. export const MAP_CONTROLS = {
  38. scale: true,
  39. toolbar: true,
  40. mousePosition: true,
  41. } as const;
  42. export interface AMapProps {
  43. style?: React.CSSProperties;
  44. width?: string | number;
  45. height?: string | number;
  46. center?: [number, number];
  47. zoom?: number;
  48. mode?: MapMode;
  49. onMarkerClick?: (markerData: MarkerData) => void;
  50. onClick?: (lnglat: [number, number]) => void;
  51. markers?: MarkerData[];
  52. showCluster?: boolean;
  53. queryKey?: string;
  54. }
  55. export interface MapConfig {
  56. zoom: number;
  57. center: [number, number];
  58. zooms: [number, number];
  59. resizeEnable: boolean;
  60. rotateEnable: boolean;
  61. pitchEnable: boolean;
  62. defaultCursor: string;
  63. showLabel: boolean;
  64. layers?: any[];
  65. }
  66. export interface AMapInstance {
  67. map: any;
  68. setZoomAndCenter: (zoom: number, center: [number, number]) => void;
  69. setCenter: (center: [number, number]) => void;
  70. setZoom: (zoom: number) => void;
  71. destroy: () => void;
  72. clearMap: () => void;
  73. getAllOverlays: (type: string) => any[];
  74. on: (event: string, handler: Function) => void;
  75. }
  76. declare global {
  77. interface Window {
  78. AMap: any;
  79. CONFIG?: GlobalConfig;
  80. }
  81. }
  82. const loadScript = (url: string,plugins:string[]): Promise<void> => {
  83. return new Promise((resolve, reject) => {
  84. const script = document.createElement('script');
  85. script.type = 'text/javascript';
  86. script.src = url + (plugins.length > 0 ? `&plugin=${plugins.join(',')}` : '');
  87. script.onerror = (e) => reject(e);
  88. script.onload = () => resolve();
  89. document.head.appendChild(script);
  90. });
  91. };
  92. export const useAMapLoader = (mode: MapMode = MapMode.ONLINE) => {
  93. return useQuery({
  94. queryKey: ['amap-loader', mode],
  95. queryFn: async () => {
  96. if (typeof window === 'undefined') return null;
  97. if (!window.AMap) {
  98. const config = mode === MapMode.OFFLINE ? AMAP_OFFLINE_CONFIG : AMAP_ONLINE_CONFIG;
  99. await loadScript(config.MAIN_JS,config.PLUGINS);
  100. }
  101. return window.AMap;
  102. },
  103. staleTime: Infinity, // 地图脚本加载后永不过期
  104. gcTime: Infinity,
  105. retry: 2,
  106. });
  107. };
  108. export const useAMapClick = (
  109. map: any,
  110. onClick?: (lnglat: [number, number]) => void
  111. ) => {
  112. const mouseTool = useRef<any>(null);
  113. const clickHandlerRef = useRef<((e: any) => void) | null>(null);
  114. useEffect(() => {
  115. if (!map) return;
  116. // 清理旧的点击处理器
  117. if (clickHandlerRef.current) {
  118. map.off('click', clickHandlerRef.current);
  119. clickHandlerRef.current = null;
  120. }
  121. // 如果有点击回调,设置新的点击处理器
  122. if (onClick) {
  123. clickHandlerRef.current = (e: any) => {
  124. const lnglat = e.lnglat.getLng ?
  125. [e.lnglat.getLng(), e.lnglat.getLat()] as [number, number] :
  126. [e.lnglat.lng, e.lnglat.lat] as [number, number];
  127. onClick(lnglat);
  128. };
  129. map.on('click', clickHandlerRef.current);
  130. }
  131. return () => {
  132. if (clickHandlerRef.current) {
  133. map.off('click', clickHandlerRef.current);
  134. clickHandlerRef.current = null;
  135. }
  136. };
  137. }, [map, onClick]);
  138. return {
  139. mouseTool: mouseTool.current
  140. };
  141. };
  142. // 定义图标配置的类型
  143. interface MarkerIconConfig {
  144. size: [number, number];
  145. content: string;
  146. }
  147. // 默认图标配置
  148. const DEFAULT_MARKER_ICON: MarkerIconConfig = {
  149. size: [25, 34],
  150. content: `
  151. <svg width="25" height="34" viewBox="0 0 25 34" fill="none" xmlns="http://www.w3.org/2000/svg">
  152. <path d="M12.5 0C5.59644 0 0 5.59644 0 12.5C0 21.875 12.5 34 12.5 34C12.5 34 25 21.875 25 12.5C25 5.59644 19.4036 0 12.5 0ZM12.5 17C10.0147 17 8 14.9853 8 12.5C8 10.0147 10.0147 8 12.5 8C14.9853 8 17 10.0147 17 12.5C17 14.9853 14.9853 17 12.5 17Z" fill="#1890ff"/>
  153. </svg>
  154. `
  155. };
  156. interface UseAMapMarkersProps {
  157. map: any;
  158. markers: MarkerData[];
  159. showCluster?: boolean;
  160. onMarkerClick?: (markerData: MarkerData) => void;
  161. }
  162. export const useAMapMarkers = ({
  163. map,
  164. markers,
  165. showCluster = true,
  166. onMarkerClick,
  167. }: UseAMapMarkersProps) => {
  168. const clusterInstance = useRef<any>(null);
  169. const markersRef = useRef<any[]>([]);
  170. // 优化经纬度格式化函数
  171. const toFixedDigit = (num: number, n: number): string => {
  172. if (typeof num !== "number") return "";
  173. return Number(num).toFixed(n);
  174. };
  175. // 创建标记点
  176. const createMarker = (markerData: MarkerData) => {
  177. const { longitude, latitude, title, iconUrl } = markerData;
  178. // 创建标记点
  179. const marker = new window.AMap.Marker({
  180. position: [longitude, latitude],
  181. title: title,
  182. icon: iconUrl ? new window.AMap.Icon({
  183. size: DEFAULT_MARKER_ICON.size,
  184. imageSize: DEFAULT_MARKER_ICON.size,
  185. image: iconUrl
  186. }) : new window.AMap.Icon({
  187. size: DEFAULT_MARKER_ICON.size,
  188. imageSize: DEFAULT_MARKER_ICON.size,
  189. image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(DEFAULT_MARKER_ICON.content)}`
  190. }),
  191. label: title ? {
  192. content: title,
  193. direction: 'top'
  194. } : undefined
  195. });
  196. // 添加点击事件
  197. if (onMarkerClick) {
  198. marker.on('click', () => onMarkerClick(markerData));
  199. }
  200. return marker;
  201. };
  202. // 处理聚合点
  203. const handleCluster = () => {
  204. if (!map || !markers.length) return;
  205. const points = markers.map(item => ({
  206. weight: 1,
  207. lnglat: [
  208. toFixedDigit(item.longitude, 5),
  209. toFixedDigit(item.latitude, 5)
  210. ],
  211. ...item
  212. }));
  213. if (clusterInstance.current) {
  214. clusterInstance.current.setData(points);
  215. return;
  216. }
  217. if(window.AMap?.MarkerCluster){
  218. clusterInstance.current = new window.AMap.MarkerCluster(map, points, {
  219. gridSize: 60,
  220. renderMarker: (context: { marker: any; data: MarkerData[] }) => {
  221. const { marker, data } = context;
  222. const firstPoint = data[0];
  223. if (firstPoint.iconUrl) {
  224. marker.setContent(`<img src="${firstPoint.iconUrl}" style="width:${DEFAULT_MARKER_ICON.size[0]}px;height:${DEFAULT_MARKER_ICON.size[1]}px;">`);
  225. } else {
  226. marker.setContent(DEFAULT_MARKER_ICON.content);
  227. }
  228. marker.setAnchor('bottom-center');
  229. marker.setOffset(new window.AMap.Pixel(0, 0));
  230. if (firstPoint.title) {
  231. marker.setLabel({
  232. direction: 'top',
  233. offset: new window.AMap.Pixel(0, -5),
  234. content: firstPoint.title
  235. });
  236. }
  237. marker.on('click', () => onMarkerClick?.(firstPoint));
  238. }
  239. });
  240. }
  241. // 优化聚合点点击逻辑
  242. if(clusterInstance.current){
  243. clusterInstance.current.on('click', (item: any) => {
  244. if (item.clusterData.length <= 1) return;
  245. const center = item.clusterData.reduce(
  246. (acc: number[], curr: any) => [
  247. acc[0] + Number(curr.lnglat[0]),
  248. acc[1] + Number(curr.lnglat[1])
  249. ],
  250. [0, 0]
  251. ).map((coord: number) => coord / item.clusterData.length);
  252. map.setZoomAndCenter(map.getZoom() + 2, center);
  253. });
  254. }
  255. };
  256. // 处理普通标记点
  257. const handleMarkers = () => {
  258. if (!map || !markers.length) return;
  259. // 清除旧的标记点
  260. markersRef.current.forEach(marker => marker.setMap(null));
  261. markersRef.current = [];
  262. // 添加新的标记点
  263. markersRef.current = markers.map(markerData => {
  264. const marker = createMarker(markerData);
  265. marker.setMap(map);
  266. return marker;
  267. });
  268. };
  269. useEffect(() => {
  270. if (!map || !Array.isArray(markers)) return;
  271. // 清理旧的标记点和聚合点
  272. if (clusterInstance.current) {
  273. clusterInstance.current.setMap(null);
  274. clusterInstance.current = null;
  275. }
  276. markersRef.current.forEach(marker => marker.setMap(null));
  277. markersRef.current = [];
  278. // 根据配置添加新的标记点
  279. if (markers.length > 0) {
  280. if (showCluster) {
  281. handleCluster();
  282. } else {
  283. handleMarkers();
  284. }
  285. }
  286. return () => {
  287. if (clusterInstance.current) {
  288. clusterInstance.current.setMap(null);
  289. clusterInstance.current = null;
  290. }
  291. markersRef.current.forEach(marker => marker.setMap(null));
  292. markersRef.current = [];
  293. };
  294. }, [map, markers, showCluster]);
  295. };
  296. const AMapComponent: React.FC<AMapProps> = ({
  297. width = '100%',
  298. height = '400px',
  299. center = TILE_CONFIG.DEFAULT_CENTER as [number, number],
  300. zoom = TILE_CONFIG.DEFAULT_ZOOM,
  301. mode = (getGlobalConfig('MAP_CONFIG')?.MAP_MODE as MapMode) || MapMode.ONLINE,
  302. onMarkerClick,
  303. onClick,
  304. markers = [],
  305. showCluster = true,
  306. queryKey = 'amap-instance',
  307. }) => {
  308. const mapContainer = useRef<HTMLDivElement>(null);
  309. const mapInstance = useRef<AMapInstance | null>(null);
  310. const queryClient = useQueryClient();
  311. // 加载地图脚本
  312. const { data: AMap, isLoading: isLoadingScript } = useAMapLoader(mode);
  313. // 初始化地图实例
  314. const { data: map } = useQuery<AMapInstance>({
  315. queryKey: [ queryKey ],
  316. queryFn: async () => {
  317. if (!AMap || !mapContainer.current) return null;
  318. const config: MapConfig = {
  319. zoom,
  320. center,
  321. zooms: [3, 20],
  322. resizeEnable: true,
  323. rotateEnable: false,
  324. pitchEnable: false,
  325. defaultCursor: 'pointer',
  326. showLabel: true,
  327. };
  328. if (mode === 'offline') {
  329. config.layers = [
  330. new AMap.TileLayer({
  331. getTileUrl: (x: number, y: number, z: number) =>
  332. `${TILE_CONFIG.BASE_URL}/${z}/${x}/${y}.png`,
  333. zIndex: 100,
  334. })
  335. ];
  336. }
  337. const newMap = new AMap.Map(mapContainer.current, config);
  338. mapInstance.current = newMap;
  339. return newMap;
  340. },
  341. enabled: !!AMap && !!mapContainer.current && !isLoadingScript,
  342. gcTime: Infinity,
  343. staleTime: Infinity,
  344. });
  345. // 处理标记点
  346. useAMapMarkers({
  347. map,
  348. markers,
  349. showCluster,
  350. onMarkerClick,
  351. });
  352. // 处理点击事件
  353. useAMapClick(map, onClick);
  354. // 更新地图视图
  355. useEffect(() => {
  356. if (!map) return;
  357. if (center && zoom) {
  358. map.setZoomAndCenter(zoom, center);
  359. } else if (center) {
  360. map.setCenter(center);
  361. } else if (zoom) {
  362. map.setZoom(zoom);
  363. }
  364. }, [map, center, zoom]);
  365. // 清理地图实例和查询缓存
  366. useEffect(() => {
  367. return () => {
  368. if (mapInstance.current) {
  369. mapInstance.current.destroy();
  370. mapInstance.current = null;
  371. // 清理 React Query 缓存
  372. queryClient.removeQueries({ queryKey: [ queryKey ] });
  373. }
  374. };
  375. }, [queryClient]);
  376. return (
  377. <div
  378. ref={mapContainer}
  379. style={{
  380. width,
  381. height,
  382. position: 'relative',
  383. }}
  384. >
  385. {isLoadingScript && <div className="w-full h-full flex justify-center items-center"><Spin /></div>}
  386. </div>
  387. );
  388. };
  389. export default AMapComponent;