Center of each side of a polygon in JavaScript


Suppose, we array of arrays like this −

const arr = [
   [-73.9280684530257, 40.8099975343718],
   [-73.9282820374729, 40.8100875554645],
   [-73.9280124002104, 40.8103130893677],
   [-73.927875543761, 40.8102554080229],
   [-73.9280684530257, 40.8099975343718]
];

Here each subarray represents a point on a 2-D plane, and each point is a vertex of n sided polygon where n is the number of subarrays in the input arrays.

We are required to write a JavaScript function that takes in one such array and returns a new array of n subarrays, each representing the midpoint of corresponding sides of the polygon.

Example

The code for this will be −

const arr = [
   [-73.9280684530257, 40.8099975343718],
   [-73.9282820374729, 40.8100875554645],
   [-73.9280124002104, 40.8103130893677],
   [-73.927875543761, 40.8102554080229],
   [-73.9280684530257, 40.8099975343718]
];
const findCenters = arr => {
   const centerArray = [];
   for(i = 0; i<arr.length; i++){
      nextIndex = (i+1) % (arr.length);
      centerArray[i] = [];
      centerArray[i][0] = (arr [i][0] + arr[nextIndex][0]) / 2;
      centerArray[i][1] = (arr[i][1] + arr[nextIndex][1]) / 2;
   };
   return centerArray;
};
console.log(findCenters(arr));

Output

The output in the console −

[
   [ -73.92817524524929, 40.81004254491815 ],
   [ -73.92814721884164, 40.8102003224161 ],
   [ -73.92794397198571, 40.8102842486953 ],
   [ -73.92797199839336, 40.81012647119735 ],
   [ -73.9280684530257, 40.8099975343718 ]
]

Updated on: 12-Oct-2020

112 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements