高德地图infoWindow content使用reactDom

发布时间 2023-08-14 15:06:47作者: ZerlinM

高德地图 API

在官方示例中 marker的content使用的字符串 如'<div>123</div>'
但我们希望使用reactDom更方便。

调用initPoint铺点,当点击该点时,弹出气泡信息。

const [currentData, setCurrentData] = useState()

const dataRef = useRef()

let infoWindow = new window.AMap.InfoWindow({ autoMove: true, offset: new window.AMap.Pixel(0, 0) });

const markerClick = (e) => {
    setCurrentData(e.target.extData)
    infoWindow.setContent(dataRef?.current);
    infoWindow.open(map, e.target.getPosition());
}

const initPoint = () => {
    const i = {
        deviceName: 'name',
        id: 1,
        num: 333,
        lng: 116.39,
        lat: 39.9,
    }

    let marker = new window.AMap.Marker({
        position: new window.AMap.LngLat(Number(i.lng), Number(i.lat)),   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
        title: i.deviceName,
        icon: ICON.iconOn,
        offset: new window.AMap.Pixel(-15, -15),

    });
    marker.extData = i;
    marker.on('click', markerClick);
    marker.emit('click', { target: marker });
    map.add(marker);
}

reactDom

return (
  <>
    {
        currentData ? <div className={s.mapCard} style={{ display: 'none' }} ref={dataRef}>
            <div className={s.title}>{currentData.deviceName}</div>
            <div className={s.num}>{currentData.num}</div>
        </div> : null
    }
  </>
)

使用 display: 'none' 隐藏气泡组件,仅用于点击时获取其内容