|React+Openlayuers 模板(学习中,持续更新)( 三 )


     
      /**
        * 创建信息框
        */
      const createInfo = () => {
        //创建overlay容器
        const overlayDom = document.createElement('div');
        overlayDom.className = 'overlayDom';
        mapDom.current?.appendChild(overlayDom);
        //创建内部信息容器
        const overlayInfo = document.createElement('div');
        overlayInfo.className = 'overlayInfo';
        overlayDom.appendChild(overlayInfo)
        //创建overlay
        const overlay = new Overlay({
          element: overlayDom // overlay包含的DOM
          autoPan: true // 当overlay超出地图边界时 , 地图自动移动
          positioning: 'bottom-center'
          offset: [0 -50
  // 偏移量 , 单位像素
          stopEvent: true // 事件传播
          autoPanAnimation: {
            // 设置autoPan的动画
            duration: 500
         
          autoPanMargin: 150
        )
        //将overlay添加到地图
        map.current.addOverlay(overlay)
        //设置地图左键点击事件
        map.current.on('click' (event: any) => {
          if (overlayInfo.innerHTML !== ' ') {
            // 清空
            reactDom.unmountComponentAtNode(overlayInfo);
         
          // 获取点击的feature
          const feature = map.current.forEachFeatureAtPixel(event.pixel function (feature: any vectorLayer: any) {
            return feature;
          )
          if (feature && feature.id_ != undefined) {
            const infoData = https://mparticle.uc.cn/api/feature.getGeometry().flatCoordinates;
            const infoDom = (<div>
              经度: {infoData[0 维度:{infoData[1

            </div>
            )
            //将overlayInfo插入infoDom
            reactDom.render(infoDom overlayInfo);
            // 设置overlay位置
            overlay.setPosition(infoData)