import React, { FC, useState, useEffect } from 'react'; import { uniqueId } from 'lodash'; import { Input, AutoComplete } from 'antd'; import { ExpansionProps, Position } from '../types'; import { lngRegexp, latRegexp } from '@/utils/regexp'; import styles from './index.less'; interface SearchAddressProps extends ExpansionProps { onChange?: (position: Position) => void; setPosition?: (position: Position) => void; } let autocomplete: any = null; const SearchAddress: FC = props => { const { __map__, onChange, setPosition } = props; const map = __map__; const [options, setOptions] = useState([]); useEffect(() => { map.plugin(['AMap.Autocomplete'], function() { try { autocomplete = new window.AMap.Autocomplete(); } catch (e) { console.log(e); } }); }, []); const handleSelect = (value: string, options: any) => { const location = options.location; if (!location) return; map?.setCenter([location.lng, location.lat]); map?.setZoom(15); onChange?.({ longitude: location.lng, latitude: location.lat, }); }; const handleSearch = (value: string) => { const splitValue = value.split(','); if ( splitValue?.length === 2 && splitValue[1] && lngRegexp.test(splitValue[0]) && latRegexp.test(splitValue[1]) && setPosition ) { setPosition?.([splitValue[0], splitValue[1]]); onChange?.([splitValue[0], splitValue[1]]); return; } if (!autocomplete) return; autocomplete.search(value, (status: string, results: any) => { if (status === 'complete') { const tips = results.tips .filter((item: any) => item.id) .map(renderItem); setOptions(tips); } }); }; const renderItem = (item: any) => { return { ...item, value: item.name, key: uniqueId('address_'), label: (
{item.name} {item.district}
), }; }; return ( ); }; export default SearchAddress;