Created
March 17, 2025 12:49
-
-
Save allenhwkim/09af53e4f7f2211da3f8b77ddd0666e1 to your computer and use it in GitHub Desktop.
calculate polygon area in square meters
This file contains 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
function calculatePolygonArea(coordinates) { | |
// Check if the polygon is closed (first and last points should match) | |
const first = coordinates[0]; | |
const last = coordinates[coordinates.length - 1]; | |
if (first[0] !== last[0] || first[1] !== last[1]) { | |
coordinates.push([...first]); // Close the polygon if not already closed | |
} | |
// Calculate average latitude for longitude scaling | |
const latitudes = coordinates.map(coord => coord[1]); | |
const avgLat = latitudes.reduce((sum, lat) => sum + lat, 0) / latitudes.length; | |
const latToKm = 111.32; // 1 degree latitude ≈ 111.32 km | |
const lonToKm = latToKm * Math.cos(avgLat * Math.PI / 180); // Adjust longitude scale by latitude | |
// Convert coordinates to kilometers relative to the first point | |
const refLon = coordinates[0][0]; | |
const refLat = coordinates[0][1]; | |
const pointsInKm = coordinates.map(([lon, lat]) => [ | |
(lon - refLon) * lonToKm, // x in km | |
(lat - refLat) * latToKm // y in km | |
]); | |
// Shoelace formula | |
let area = 0; | |
for (let i = 0; i < pointsInKm.length - 1; i++) { | |
const [x1, y1] = pointsInKm[i]; | |
const [x2, y2] = pointsInKm[i + 1]; | |
area += (x1 * y2) - (y1 * x2); | |
} | |
// Final area in square kilometers | |
area = Math.abs(area) / 2; | |
return area; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment