代码之家  ›  专栏  ›  技术社区  ›  Anders Gjerde

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

  •  2
  • Anders Gjerde  · 技术社区  · 8 年前

    Openlayers为绘制长方体和矩形提供了有用的功能,并且具有ol。geom。几何学原型旋转(角度,锚点)用于围绕某个锚点旋转几何体。修改长方体/矩形时是否可以锁定其旋转?

    使用OpenLayers示例 here 要绘制具有特定旋转的长方体来说明该点,请执行以下操作:

    Modifying a rotated box/rectangle polygon

    我希望长方体/矩形保持旋转,同时仍然能够将边拖得更长、更短。有没有一个简单的方法来实现这一点?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Anders Gjerde    7 年前

    回答我提出的解决方案。

    首先,将特征添加到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);
    }
    

    ChangeFeature函数如下。只要用户仍在修改/拖动其中一个角,对几何体所做的每一次更改都会调用此函数。在这个函数中,我制作了另一个函数,将修改后的矩形再次调整为矩形。此“Rectanglify”功能移动与用户刚刚移动的角点相邻的角点。

    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);
    }
    

    在不涉及太多细节的情况下,rectanglify函数需要

    1. 以弧度查找几何体的旋转
    2. 以弧度*-1反向旋转(例如,几何体。旋转(弧度*(-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);
    }