123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- import React, { useEffect, useRef, useState } from 'react';
- import { sdk } from '@/utils/map'
- import { newMarker, autoPos, autoPoi } from './utils'
- import './style.less'
-
- const plugins = ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geolocation', 'AMap.Autocomplete', 'AMap.PlaceSearch']
-
- export default (props) => {
- const map = useRef()
- const container = useRef()
- const inputRef = useRef()
- const posMarker = useRef()
- const [currentPos, setCurrentPos] = useState([]);
-
- const handleClick = (e) => {
- const { lnglat } = e
- const pos = [lnglat.getLng(), lnglat.getLat()]
- posMarker.current.setMap(map.current);
- setCurrentPos(pos)
- props.onChange(pos.join(','))
- }
-
- useEffect(() => {
- // 只加载一次 amap 相关 js
- sdk.loadMapModule({ plugins }).then((AMap) => {
- const instance = new AMap.Map(container.current, { zoom: 12 })
- instance.addControl(new AMap.Scale())
- instance.addControl(new AMap.ToolBar())
-
- // 尝试自动定位到当前位置
- if (!props.value) {
- instance.addControl(autoPos(AMap))
- }
-
- // 当前选中点 - 初始的时候没有定位
- posMarker.current = newMarker(AMap, {
- active: true,
- position: props.value ? props.value.split(',') : undefined,
- })
-
- if (props.value) {
- posMarker.current.setMap(instance);
- }
-
- // POI 搜索
- autoPoi(instance, AMap, inputRef, { click: handleClick })
-
- instance.on('click', handleClick);
- map.current = instance
- })
- }, [])
-
- useEffect(() => {
- if (props.value) {
- setCurrentPos(props.value.split(','))
- }
- }, [props.value])
-
- useEffect(() => {
- if (currentPos.length) {
- if (posMarker.current) {
- posMarker.current.setPosition(currentPos)
- }
- if (map.current) {
- map.current.setCenter(currentPos);
- }
- if (currentPos.length && map.current) {
- posMarker.current.setMap(map.current)
- }
- }
- }, [currentPos])
-
- const boxStyle = {
- width: '100%',
- height: '400px',
- position: 'relative',
- ...(props.style || {}),
- }
-
- const mapStyle = {
- height: '100%',
- width: '100%',
- margin: 0,
- }
-
- const inputStyle = {
- width: '200px',
- padding: '5px',
- position: 'absolute',
- zIndex: 9999,
- right: '30px',
- lineHeight: '1em',
- }
-
- const inputSty1 = {
- ...inputStyle,
- top: '50px',
- }
-
- const inputSty2 = {
- ...inputStyle,
- top: '10px',
- background: 'rgba(255, 255, 255, .9)',
- border: '1px solid #bbb',
- }
-
- return (
- <div className={props.className} style={boxStyle}>
- <div ref={container} style={mapStyle} id="poi-map-wrapper"></div>
- <input placeholder="请输入搜索关键字" ref={inputRef} style={inputSty1} />
- <input value={`坐标: ${currentPos.join(',')}`} style={inputSty2} disabled />
- </div>
- )
- }
|