mapbox地图,地图框选范围之后, 禁止拖动该框选范围

451 阅读1分钟

(摘抄的,暂做记录, 后续理解之后,会更新完善)

创建 drawSimpleSelect.js(随便叫啥)

import * as MapboxDraw from '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw';
import * as Constants from '@mapbox/mapbox-gl-draw/src/constants';
import * as CommonSelectors from '@mapbox/mapbox-gl-draw/src/lib/common_selectors';

const SimpleSelectWithoutMiddleVertexMode = MapboxDraw.modes.simple_select;

SimpleSelectWithoutMiddleVertexMode.onTap = SimpleSelectWithoutMiddleVertexMode.onClick = function (state, e) {
  // 目的是为了避免绘制区域被选中而被拖拽编辑(clickOnFeature)等操作。自带属性没有发现可以实现这种功能
  // Click (with or without shift) on no feature
  if (CommonSelectors.noTarget(e)) return this.clickAnywhere(state, e); // also tap
  if (CommonSelectors.isOfMetaType(Constants.meta.VERTEX)(e)) return this.clickOnVertex(state, e); //tap
  if (CommonSelectors.isFeature(e)) return; // 直接return 简单粗暴 而不是this.clickOnFeature(state, e);
};

export default SimpleSelectWithoutMiddleVertexMode;

在需要用到的文件中添加

import SimpleSelectWithoutMiddleVertexMode from '../utils/drawSimpleSelect';


/**
 * 添加绘图工具
 */
const modes = MapboxDraw.modes;

export const ADD_DRAW = () => {
  if (draw) {
    REMOVE_DRAW();
  }

  draw = new MapboxDraw({
    displayControlsDefault: false,
    controls: {
      polygon: true,
      trash: false,
    },
    defaultMode: 'draw_polygon',
    boxSelect: false,
    touchEnabled: false,
    keybindings: false,
    modes: {
      ...MapboxDraw.modes, // draw_rectangle // mapboxgl-draw-rectangle-drag
      // draw_rectangle: DrawRectangle,
      simple_select: SimpleSelectWithoutMiddleVertexMode, // 取消MapboxDraw自定义取消选中功能
    },
  });
  map.addControl(draw, 'bottom-right');
  //绘制好的框选框禁止拖动
  modes.simple_select.onDrag = function (state, e) {
    //when polygon is deselected onDrag will be false and user not be able to drag it
    // console.log(state, e);

    return;
  };
};

image.png