Search code examples
turfjs

Move polygon points based on center location?


Would someone have an example using Turf moving all polygon points from one location to another based on a new center point?

For example, let’s say I have calculated a center based on where the points were originally created.

Then I need to move those points to a new location based on that calculated center.

As always any help would be great!


Solution

  • You need to use transformTranslate

    var poly = turf.polygon([[[0,29], [3.5,29], [2.5,32], [0,29]]]);
    
    //calculates the centroid of the polygon
    var center = turf.centroid(poly);
    
    var from = turf.point([center.geometry.coordinates[0], center.geometry.coordinates[1]]);
    
    var to = turf.point([4, 35]);
    
    //finds the bearing angle between the points
    var bearing = turf.rhumbBearing(from, to);
    
    //calculates the distance between the points
    var distance = turf.rhumbDistance(from, to);
    
    //moves the polygon to the distance on the direction angle.
    var translatedPoly = turf.transformTranslate(poly, distance, bearing)
    

    enter image description here