Search code examples
javascriptopenlayers

How to move a selection starting from a point in OpenLayer?


I'm trying to reproduce this kind of behaviour:

I've a selection based on an ol.interaction.Transform, just like in this example: https://viglino.github.io/ol-ext/examples/interaction/map.interaction.transform.html

Then i add a new Draw of type "Point" to the map, to select a point into the map itself.

The question is: How i can create a new selection who have this properties:

  1. The center is the point i drew on map.
  2. The 4 angles have same distance from the center just as the previous selection

I've the coordinates of the point (x,y) I've the coordinates of the previous selection rectangle (so five couple of coordinates)

var newCoordinate = [];
var newCoordinateArray = [];
var newSelection = originalSelection.clone();
     for (i = 0; i < newSelection.getGeometry().getCoordinates()[0].length; i++) {
        var x = getDifference( coordinatePunto.getGeometry().getCoordinates([0],newSelection.getGeometry().getCoordinates()[0][i][0])
        var y = getDifference( coordinatePunto.getGeometry().getCoordinates()[1],newSelection.getGeometry().getCoordinates()[0][i][1])
        newCoordinateArray.push([newSelection.getGeometry().getCoordinates()[0][i][0] - x,newSelection.getGeometry().getCoordinates()[0][i][1] + y]);
     } 
newCoordinate.push(newCoordinateArray);
newSelection.getGeometry().setCoordinates(newCoordinate);
transform.select(newSelection, true);
function getDifference(a, b) {
  return Math.abs(a - b);

 }

originalSelection contains the 5 couple of old coordinates

newSelection is the var i'm trying to populate with all the coordinates i need to show a selection with same angles (so same rectangle) but in a different place of the map (where the center is my point)


Solution

  • According with comments, that's the solution:

    var oldExtend = originalSelection.getGeometry().getExtent();
    var oldCenter = ol.extent.getCenter(oldExtend);
    var newExtend = coordinatePunto.getGeometry().getExtent();
    var newCenter = ol.extent.getCenter(newExtend);
    

    You can just translate giving new coordinates:

    newSelection.getGeometry().translate(newCenter[0] - oldCenter[0], newCenter[1] - oldCenter[1]);