openlayer对接后端智能算法中的坐标系

53 阅读1分钟

openlayer对接python算法中返回的坐标系,openlayer的坐标系是左下角为坐标原点,python返回的坐标原点为左上角,所以需要在添加交互后对坐标进行一次转化,同样,当回显的时候仍然需要将坐标转化显示到openlayer中

  1. 第一步,初始化map
function initMap() {
  const projection = new Projection({  // 投影,这里用的是像素为单位,实际开发过程中可跟需求定义。
    code: "xkcd-image",
    units: "pixels",
    extent: extent,
  });
  const raster = new TileLayer({
    source: new OSM({
      attributions: "",
    })
  });
  // 没有找到可以动态添加source的方法,所以只能在这里添加
  source = new VectorSource({ wrapX: false });
  let features = showShapes()
  source.addFeatures(features)
  vectorLayer = new VectorLayer({
    source,
  });
  map = new Map({
    layers: [raster, vectorLayer],
    target: "map",
    view: new View({
      center: getCenter(extent),
      zoom: 4,
      maxZoom: 4,
      minZoom: 4,
      projection: projection,
    }),
    extent: extent,
  });
  let pan = getPan();
  pan.setActive(false); //false禁止拖拽,true允许拖
  addInterceptor();
}
  1. 辅助函数,图层不允许拖拽,因为我这里需要在标注的是一段视频,为了防止视频尺寸和标注的尺寸有偏差,所以这里禁止了拖动
function getPan() {
  let pan = null;
  map.getInteractions().forEach((element) => {
    if (element instanceof DragPan) {
      pan = element;
    }
  });
  return pan;
}
    • 第二步添加形状
// 添加形状
function addInterceptor() {
  draw = new Draw({
    source: source,
    type: "Circle",
    geometryFunction: createBox(),
  });
  draw.on("drawend", function (event) {
    let extent_ = event.feature.getGeometry().extent_;
    let leftTopX = Math.ceil(extent_[0]);
    let leftTopY = Math.ceil(extent[3] - Math.ceil(extent_[1]));
    let rightBtmX = Math.ceil(extent_[2]);
    let rightBtmY = Math.ceil(extent[3] - Math.ceil(extent_[3]));
    identifyPosition = { leftTopX, leftTopY, rightBtmX, rightBtmY }
    draw.setActive(false); // 只允许画一个
  });
  map.addInteraction(draw);
}
  1. 第三步回显shape,回显的时候这里的数据是在添加形状控制台打印出来的坐标,在这里定义了一下而已。
// 回显形状
let position = {
  leftTopX: 464,
  leftTopY: 325,
  rightBtmX: 543,
  rightBtmY: 252,
};
let height = 500;
function showShapes() {
  let pointArr = [
    [position.leftTopX, height - position.rightBtmY],
    [position.leftTopX, height - position.leftTopY],
    [position.rightBtmX || position.rightBtmx, height - position.leftTopY],
    [position.rightBtmX || position.rightBtmx, height - position.rightBtmY],
    [position.leftTopX, height - position.rightBtmY],
  ];
  features.push(
    new Feature({
      geometry: new Polygon([pointArr]),
    })
  );
  return features
}