不同图层样式相互影响 openlayers

Different layer styles affecting each other openlayers

我想用open layers Draw方法画虚线和直线。在这种方法中,有一个用于绘制直线的 LineString 选项,但我找不到用于虚线的选项。所以我的目标是设计 LineString 的样式并制作一条虚线。但问题是,即使我将它们保持在不同的层中,这种方法也会影响直线样式。

import map from "./main.js";
const lineString = document.querySelector("#lineString");
const lineDashed = document.querySelector("#lineDashed");
let checkString = false;
let checkDashed = false;

const lineStringSource = new ol.source.Vector();
let stringLayer = new ol.layer.Vector({
  source: lineStringSource,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: "#ffcc33",
      width: 2,
    }),
  }),
});
const dashStringSource = new ol.source.Vector();
let dashLayer = new ol.layer.Vector({
  source: dashStringSource,
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      width: 2,
      lineDash: [1, 20],
    }),
  }),
});
map.addLayer(stringLayer);
map.addLayer(dashLayer);
lineString.addEventListener("click", () => {
  if (checkString === false) {
    lineString.checked = true;
    lineDashed.checked = false;
    checkDashed = false;
    checkString = true;
    addInteraction(lineStringSource);
  } else {
    lineString.checked = false;
    lineDashed.checked = false;
    checkString = false;
    checkDashed = false;
  }
});
lineDashed.addEventListener("click", () => {
  if (checkDashed === false) {
    lineString.checked = false;
    lineDashed.checked = true;
    checkDashed = true;
    checkString = false;
    addInteraction(dashStringSource);
  } else {
    lineString.checked = false;
    lineDashed.checked = false;
    checkDashed = false;
  }
});
let drawStringLine, drawDashLine;
function addInteraction(sourceType) {
  if (sourceType === lineStringSource) {
    drawStringLine = new ol.interaction.Draw({
      source: sourceType,
      type: "LineString",
    });
    map.addInteraction(drawStringLine);
  } else {
    drawDashLine = new ol.interaction.Draw({
      source: sourceType,
      type: "LineString",
    });
    map.addInteraction(drawDashLine);
  }
}

LineString 和 lineDashed 是输入单选。每当用户 select 这种输入类型之一时,我希望他们能够绘制该选项。但是上面的代码问题是当我 select lineDash 和 lineString 一样也是黄色的。如果我 select lineDash 然后再次 select lineString 这次 lineString 上有破折号样式。这个问题也影响了地图上已有的线。

您需要先删除旧交互,然后才能创建和添加新交互

let drawStringLine, drawDashLine;
function addInteraction(sourceType) {
  if (sourceType === lineStringSource) {
    map.removeInteraction(drawDashLine);
    drawStringLine = new ol.interaction.Draw({
      source: sourceType,
      type: "LineString",
    });
    map.addInteraction(drawStringLine);
  } else {
    map.removeInteraction(drawStringLine);
    drawDashLine = new ol.interaction.Draw({
      source: sourceType,
      type: "LineString",
    });
    map.addInteraction(drawDashLine);
  }
}