OpenLayers - 在修改时锁定框或矩形几何体的旋转

时间:2017-11-20 11:29:45

标签: openlayers-3

Openlayers为绘制框和矩形提供了有用的功能,并且还具有ol.geom.Geometry.prototype.rotate(angle,anchor),用于围绕某个锚点旋转几何体。是否可以在修改时锁定框/矩形的旋转?

使用位于here的OpenLayers示例绘制具有特定旋转的框以说明该点:

Modifying a rotated box/rectangle polygon

我希望盒子/矩形能够保持其旋转,同时仍能够将侧面拖得更长更短。有没有一种简单的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

回答我想出的解决方案。

首先,将特征添加到ModifyInteraction中,以便您可以通过拖动特征的角来进行修改。

this.modifyInteraction = new Modify({
    deleteCondition: eventsCondition.never,
    features: this.drawInteraction.features,
    insertVertexCondition: eventsCondition.never,
});
    this.map.addInteraction(this.modifyInteraction);

此外,在事件“ modifystart”和“ modifyend”上添加事件处理程序。

this.modifyInteraction.on("modifystart", this.modifyStartFunction);
this.modifyInteraction.on("modifyend", this.modifyEndFunction);

“ modifystart”和“ modifyend”函数看起来像这样。

private modifyStartFunction(event) {
    const features = event.features;
    const feature = features.getArray()[0];
    this.featureAtModifyStart = feature.clone();
    this.draggedCornerAtModifyStart = "";
    feature.on("change", this.changeFeatureFunction);
}

private modifyEndFunction(event) {
    const features = event.features;
    const feature = features.getArray()[0];
    feature.un("change", this.changeFeatureFunction);

    // removing and adding feature to force reindexing
    // of feature's snappable edges in OpenLayers
    this.drawInteraction.features.clear();
    this.drawInteraction.features.push(feature);
    this.dispatchRettighetModifyEvent(feature);
}

changeFeatureFunction在下面。只要用户仍在修改/拖动角部之一,对几何体所做的每一次更改都将调用此函数。在此函数内部,我做了另一个函数,将修改后的矩形再次调整为矩形。此“重新排列”功能可移动与用户刚移动的角相邻的角。

private changeFeatureFunction(event) {
    let feature = event.target;
    let geometry = feature.getGeometry();

    // Removing change event temporarily to avoid infinite recursion
    feature.un("change", this.changeFeatureFunction);

    this.rectanglifyModifiedGeometry(geometry);

    // Reenabling change event
    feature.on("change", this.changeFeatureFunction);
}

无需过多介绍,矩形函数就需要

  1. 查找以弧度为单位的几何旋转
  2. 以弧度* -1反向旋转(例如geometry.rotate(弧度*(-1),锚点))
  3. 更新拖动角的相邻角(当我们有一个与x和y轴平行的矩形时,更容易这样做)
  4. 以我们在1中发现的旋转向后旋转

-

为了获得矩形的旋转,我们可以这样做:

export function getRadiansFromRectangle(feature: Feature): number {
    const coords = getCoordinates(feature);

    const point1 = coords[0];
    const point2 = coords[1];
    const deltaY = (point2[1] as number) - (point1[1] as number);
    const deltaX = (point2[0] as number) - (point1[0] as number);

    return Math.atan2(deltaY, deltaX);
}