mnpenner

getCentroid of Polygon

Sep 29th, 2019
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. interface Point {
  2.     readonly lat: number;
  3.     readonly lng: number;
  4. }
  5.  
  6. function getArea(points: ReadonlyArray<Point>): number {
  7.     let area = 0,
  8.         i,
  9.         j,
  10.         point1,
  11.         point2;
  12.  
  13.     for (i = 0, j = points.length - 1; i < points.length; j=i,++i) {
  14.         point1 = points[i];
  15.         point2 = points[j];
  16.         area += point1.lng * point2.lat
  17.         area -= point1.lat * point2.lng;
  18.     }
  19.     area /= 2;
  20.  
  21.     return area;
  22. }
  23.  
  24. function getCentroid(points: ReadonlyArray<Point>): Point {
  25.     let x = 0,
  26.         y = 0,
  27.         i,
  28.         j,
  29.         f,
  30.         point1,
  31.         point2;
  32.  
  33.     for (i = 0, j = points.length - 1; i < points.length; j=i,++i) {
  34.         point1 = points[i];
  35.         point2 = points[j];
  36.         f = point1.lng * point2.lat - point2.lng * point1.lat;
  37.         x += (point1.lng + point2.lng) * f;
  38.         y += (point1.lat + point2.lat) * f;
  39.     }
  40.  
  41.     f = getArea(points) * 6;
  42.  
  43.     return {lng:x / f, lat: y / f};
  44. }
Add Comment
Please, Sign In to add comment