AMap.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { AMap } from '@/components';
  2. import usePlaceSearch from '@/components/AMapComponent/hooks/PlaceSearch';
  3. import { Input, Modal, Select } from 'antd';
  4. import { debounce } from 'lodash';
  5. import { Marker } from 'react-amap';
  6. import { useEffect, useState } from 'react';
  7. import './style';
  8. interface Props {
  9. value: any;
  10. close: () => void;
  11. ok: (data: any) => void;
  12. }
  13. type MarkerPointType = {
  14. longitude: number;
  15. latitude: number;
  16. };
  17. export default (props: Props) => {
  18. const [markerCenter, setMarkerCenter] = useState<MarkerPointType>({ longitude: 0, latitude: 0 });
  19. const [map, setMap] = useState<any>(null);
  20. const { data, search } = usePlaceSearch(map);
  21. const [value, setValue] = useState<any>(props.value);
  22. const onSearch = (value1: string) => {
  23. search(value1);
  24. };
  25. useEffect(() => {
  26. setValue(props?.value || '');
  27. const list = (props?.value || '').split(',') || [];
  28. if (!!props.value && list.length === 2) {
  29. setMarkerCenter({
  30. longitude: list[0],
  31. latitude: list[1],
  32. });
  33. }
  34. }, [props.value]);
  35. console.log(markerCenter);
  36. return (
  37. <Modal
  38. visible
  39. title="地理位置"
  40. width={'55vw'}
  41. onCancel={() => props.close()}
  42. onOk={() => {
  43. props.ok(value);
  44. }}
  45. >
  46. <div className={'map-search-warp'}>
  47. <div className={'map-search-select'}>
  48. <Select
  49. showSearch
  50. allowClear
  51. options={data}
  52. filterOption={false}
  53. onSearch={debounce(onSearch, 300)}
  54. style={{ width: '100%', marginBottom: 10 }}
  55. onSelect={(key: string, node: any) => {
  56. setValue(key);
  57. setMarkerCenter({
  58. longitude: node.lnglat.lng,
  59. latitude: node.lnglat.lat,
  60. });
  61. }}
  62. />
  63. <Input value={value} readOnly />
  64. </div>
  65. <AMap
  66. style={{
  67. height: 500,
  68. width: '100%',
  69. }}
  70. center={markerCenter.longitude ? markerCenter : undefined}
  71. onInstanceCreated={setMap}
  72. events={{
  73. click: (e: any) => {
  74. setValue(`${e.lnglat.lng},${e.lnglat.lat}`);
  75. setMarkerCenter({
  76. longitude: e.lnglat.lng,
  77. latitude: e.lnglat.lat,
  78. });
  79. },
  80. }}
  81. >
  82. {markerCenter.longitude ? (
  83. // @ts-ignore
  84. <Marker kye={'marker'} position={markerCenter} />
  85. ) : null}
  86. </AMap>
  87. </div>
  88. </Modal>
  89. );
  90. };