react+openlayers实现点要素的创建及其点上overlay叠加层的实现
    		       		warning:
    		            这篇文章距离上次修改已过442天,其中的内容可能已经有所变动。
    		        
        		                
                
import React, { useState, useRef } from 'react';
import 'ol/ol.css';
import { Map, View } from 'ol';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import { OSM, Vector as VectorSource } from 'ol/source';
import { Circle as CircleStyle, Fill, Stroke, Style } from 'ol/style';
import { Draw, Modify, Snap } from 'ol/interaction';
import { Point } from 'ol/geom';
import Overlay from 'ol/Overlay';
 
const App = () => {
  const [map] = useState(new Map({
    target: 'map',
    layers: [
      new TileLayer({
        source: new OSM(),
      }),
    ],
    view: new View({
      center: [0, 0],
      zoom: 2,
    }),
  }));
 
  const [draw, setDraw] = useState(new Draw({
    source: new VectorSource(),
    type: 'Point',
  }));
 
  const [overlay] = useState(new Overlay({
    element: document.getElementById('popup'),
    positioning: 'bottom-center',
    stopEvent: false,
    insertFirst: false,
  }));
 
  const createPoint = (coordinates) => {
    const feature = new VectorLayer({
      source: new VectorSource({
        features: [
          new Style({
            image: new CircleStyle({
              radius: 7,
              fill: new Fill({ color: 'blue' }),
              stroke: new Stroke({ color: 'white', width: 2 }),
            }),
            geometry: new Point(coordinates),
          }),
        ],
      }),
    });
    map.addLayer(feature);
  };
 
  const handleClick = (event) => {
    const coordinate = event.coordinate;
    createPoint(coordinate);
    overlay.setPosition(coordinate);
  };
 
  useRef(map.on('click', handleClick)).current;
 
  return (
    <div id="map">
      <div id="popup" className="ol-popup">
        <a href="#" className="ol-popup-close-box">×</a>
        <div className="ol-popup-content">
          <p>Hello, this is a popup.</p>
        </div>
        <div className="ol-popup-tip" />
      </div>
    </div>
  );
};
 
export default App;这段代码实现了在React组件中使用OpenLayers创建点要素并在点上显示Overlay叠加层的功能。首先,我们创建了一个地图实例,并定义了一个createPoint函数来创建点要素,并将其添加到地图上。在地图上的点击事件中,我们调用createPoint函数来创建点,并设置Overlay的位置。
评论已关闭