OpenLayers绘制多边形边界图层

OpenLayers绘制多边形边界图层

徐徐
前端
发布于2024-10-17 09:26:49
🌺前言
OpenLayers绘制多边形边界图层

1.准备多边形图层

地图初始化略

typescript
const vectorLayer = new VectorLayer({
        style: new Style({
            //图层样式
            fill: new Fill({
                //填充颜色
                color: 'rgba(128,216,255,0.1)',
            }),
            stroke: new Stroke({
                color: '#0091ea', //边框颜色
                width: 2, // 边框宽度
            }),
            image: new Circle({
                radius: 5,
                stroke: new Stroke({
                    color: '#FF0000', //边框颜色
                    width: 3,
                }),
                fill: new Fill({
                    color: '#ffffff', //填充颜色
                }),
            }),

        }),

        className: "polygonLayer",
        visible: false,
    });

2.根据边界坐标点绘制图形

typescript
    function drawPolygon(boundary: any[]) {
        // 将高地图的经纬度格式转换为OpenLayers所需的格式
        const coordinates = boundary.map((point: Record<string, number>) => {
            const lat = point.lat
            const lng = point.lng
            return fromLonLat([lat, lng], 'EPSG:4326')
        })
        // 创建多边形几何
        const polygon = new Polygon([coordinates]);
        // 创建矢量特征
        const feature = new Feature(polygon);
        // 添加到矢量源
        const vectorSource = new Vector({

        });
        vectorSource.addFeature(feature);
        map.getLayers()
            .getArray()
            .forEach((layer) => {
                if (layer.getClassName() === 'polygonLayer') {
                    layer.setSource(vectorSource)
                    layer.setVisible(true)  
                }
            });
    }

3.让地图中心和缩放比自适应

typescript
 map.getLayers()
    .getArray()
    .forEach((layer) => {
        if (layer.getClassName() === 'polygonLayer') {
            const extent = layer.getSource().getExtent()
            extent && map.getView().fit(extent, { duration: 2 });
        }
    });

目录

文章最后更新于 2024-10-17 10:12:07
留言
暂无数据

~~空空如也