百度地图控件自由画多边形

    // 范围选择
    rangeQuery() {
        // 禁用地图的默认交互
        this.disableMapInteractions()
        
        this.clearLayer('searchLayer')
        
        // 先清除之前的圈圈
        if (this.drawLayer) {
            this.drawLayer.getSource().clear()
        }
        
        // 创建绘图图层(如果还没创建)
        if (!this.drawLayer) {
            this.drawSource = new VectorSource();
            this.drawLayer = new VectorLayer({
                source: this.drawSource,
                style: new Style({
                    stroke: new Stroke({
                        color: '#ff3264',
                        width: 5
                    })
                })
            });
            mapContainer.addLayer(this.drawLayer)
        }
    
        // 如果已存在绘图交互,先移除它
        if (this.draw) {
            mapContainer.removeInteraction(this.draw)
        }
    
        // 创建新的绘图交互
        this.draw = new Draw({
            source: this.drawSource,
            type: 'LineString',
            freehand: true, // 启用自由手绘模式
            style: new Style({
                stroke: new Stroke({
                    color: '#ff3264',
                    width: 5
                })
            })
        })
    
        // 添加绘图交互到地图
        mapContainer.addInteraction(this.draw)
    
        // 监听绘图完成事件
        this.draw.on('drawstart', (event) => {
            this.sketch = event.feature
        })
        
        this.draw.on('drawend', (event) => {
            const lineString = event.feature.getGeometry()
            const coordinates = lineString.getCoordinates()
            
            if (coordinates.length >= 3) {
                coordinates.push(coordinates[0])
                const polygon = new Polygon([coordinates])
                const polygonFeature = new Feature(polygon)
              
                this.drawSource.removeFeature(event.feature)
                this.drawSource.addFeature(polygonFeature)
    
                this.sendToServer()
            } else {
              console.log('至少需要3个点来形成一个有效的多边形');
            }
    
            this.enableMapInteractions()
        })
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容