leaflet清除通过geoman(pm)插件绘制的图形

leaflet清除通过geoman(pm)插件绘制的图形

项目使用geoman第三方组件,来实现绘制图形。现在项目需要把绘制的图形清理下。
leaflet已经封装好了从地图上移除图形方法。需要做的就是获取到绘制的layer,然后调用下map.removeLayer(layer);

启用Geoman绘制工具条

 onEnableTool(){
   this.map.pm.setLang('zh');
        this.map.pm.addControls({
          position: 'topright',
          drawCircle: false,
          drawRectangle: false,
          drawCircleMarker: false,
        });
 }
 //这里我是关闭了绘制点、矩形和圆的按钮。

监听绘制图形

init(){
 
 this.map.on('pm:create', (workingLayer) => {           
        const graphic = LMapUtil.getGraphics(workingLayer);       
        vm.map.graphics.push(workingLayer);//这里记录绘制结果信息        
        this.$emit('edited', graphic);
      });
}

清除图形方法

//注意:graphic.layer才是真正添加到map的图层;不是graphic。
clearGraphics(map){
 map.graphics.forEach(graphic =>{
 map.removeLayer(graphic.layer);
 })
}

注意:graphic.layer才是真正添加到map的图层;不是graphic。
刚开始我把workingLayer当作添加到map的图层,然后移除发现不行,图形还是存在,网上也没有找到方法,只好下载geoman的源码来研究它是怎么添加到地图和返回参数是什么。
最后在绘制Marker源码中发现如下代码:

_createMarker(e) {
    if (!e.latlng) {
      return;
    }

    // assign the coordinate of the click to the hintMarker, that's necessary for
    // mobile where the marker can't follow a cursor
    if (!this._hintMarker._snapped) {
      this._hintMarker.setLatLng(e.latlng);
    }

    // get coordinate for new vertex by hintMarker (cursor marker)
    const latlng = this._hintMarker.getLatLng();

    // create marker
    const marker = L.circleMarker(latlng, this.options.pathOptions);
    // add marker to the map
    marker.addTo(this._map);

    // enable editing for the marker
    marker.pm.enable();

    // fire the pm:create event and pass shape and marker
    this._map.fire('pm:create', {
      shape: this._shape,
      marker, // DEPRECATED
      layer: marker,
    });

    this._cleanupSnapping();
  },

Geoman源码地址
Geoman帮助文档

你可能感兴趣的:(Leaflet,Geoman)