amap.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React, { useState } from 'react';
  2. import type { MapProps } from 'react-amap';
  3. import { Map } from 'react-amap';
  4. import { getAMapUiPromise } from './APILoader';
  5. import SystemConst from '@/utils/const';
  6. import { Empty } from 'antd';
  7. interface AMapProps extends Omit<MapProps, 'amapkey' | 'useAMapUI'> {
  8. style?: React.CSSProperties;
  9. className?: string;
  10. AMapUI?: string | boolean;
  11. }
  12. export default (props: AMapProps) => {
  13. const { style, className, events, onInstanceCreated, ...extraProps } = props;
  14. const [uiLoading, setUiLoading] = useState(false);
  15. const isOpenUi = 'AMapUI' in props || props.AMapUI;
  16. const amapKey = localStorage.getItem(SystemConst.AMAP_KEY);
  17. const getAMapUI = () => {
  18. const version = typeof props.AMapUI === 'string' ? props.AMapUI : '1.1';
  19. getAMapUiPromise(version).then(() => {
  20. setUiLoading(true);
  21. });
  22. };
  23. const onCreated = (map: any) => {
  24. if (onInstanceCreated) {
  25. onInstanceCreated(map);
  26. }
  27. if (isOpenUi) {
  28. getAMapUI();
  29. }
  30. };
  31. return (
  32. <div style={style || { width: '100%', height: '100%' }} className={className}>
  33. {amapKey ? (
  34. // @ts-ignore
  35. <Map
  36. version={'2.0'}
  37. amapkey={amapKey}
  38. zooms={[3, 20]}
  39. events={
  40. events
  41. ? {
  42. ...events!,
  43. created: onCreated,
  44. }
  45. : {
  46. created: onCreated,
  47. }
  48. }
  49. {...extraProps}
  50. >
  51. {isOpenUi ? (uiLoading ? props.children : null) : props.children}
  52. </Map>
  53. ) : (
  54. <Empty description={'请配置高德地图key'} />
  55. )}
  56. </div>
  57. );
  58. };