Last active
February 7, 2020 21:28
-
-
Save fongreecss/7afdf8c8cd6fa50141b575c9f0baace3 to your computer and use it in GitHub Desktop.
Calc distance between 2d points and poly area
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Polygon { | |
static calcArea (...points) { | |
var area = 0; | |
var X = points.map((v) => { return v[0] }); | |
var Y = points.map((v) => { return v[1] }); | |
var numPoints = points.length; | |
var j = numPoints - 1; | |
var i = 0; | |
for (i; i<numPoints; i++) | |
{ area += (X[j]+X[i]) * (Y[j]-Y[i]); | |
j = i; | |
} | |
return Math.abs(area/2); | |
} | |
} | |
class Distance { | |
calcDistance (point1, point2) { | |
//return Math.sqrt( Math.pow((point2[0]-point1[0]), 2) + Math.pow((point2[1]-point1[1]), 2) ); | |
return Math.hypot(point2[0]-point1[0], point2[1]-point1[1]); | |
} | |
constructor(point1, point2) { | |
this.X1 = point1[0]; | |
this.Y1 = point1[1]; | |
this.X2 = point2[0]; | |
this.Y2 = point2[1]; | |
this.distance = this.calcDistance(point1, point2); | |
} | |
} | |
/** | |
* Usage | |
*/ | |
var tA = [560435, 163627]; | |
var tB = [560480, 163657]; | |
var tC = [560447, 163734]; | |
var tD = [560429, 163740]; | |
var tE = [560406, 163794]; | |
var tF = [560387, 163783]; | |
var allPoints = { | |
"AB" : new Distance(tA, tB), | |
"BC" : new Distance(tB, tC), | |
"CD" : new Distance(tC, tD), | |
"DE" : new Distance(tD, tE), | |
"EF" : new Distance(tE, tF), | |
"FA" : new Distance(tF, tA), | |
} | |
console.table(allPoints); | |
var areaBig = Polygon.calcArea(tA, tB, tC, tD, tE, tF); | |
var areaSmall = Polygon.calcArea([0,0], [1,0], [1,-1], [0, -1]); | |
console.log(areaBig); | |
console.log(areaSmall); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment