Skip to content

Instantly share code, notes, and snippets.

@coryasilva
Created February 6, 2024 19:57
Show Gist options
  • Save coryasilva/e3bbe0c6b3d7879fd1b00068f470b537 to your computer and use it in GitHub Desktop.
Save coryasilva/e3bbe0c6b3d7879fd1b00068f470b537 to your computer and use it in GitHub Desktop.
Calculate geometric bounds and center
const points = [
// Bounds
[32.8644429,-117.2791394]
, [32.8693815,-117.0464238]
, [32.6162867,-116.9453358]
, [32.5781068,-117.1498078]
// Points inside
, [32.6, -117.1]
, [32.7, -117.2]
]
function getCenter(x1, y1, x2, y2) {
const center = [0, 0]
center[0] = x1 + ((x2 - x1) / 2)
center[1] = y1 + ((y2 - y1) / 2)
return center
}
function getBounds(points) {
const bounds = [Infinity, Infinity, -Infinity, -Infinity];
points.forEach( orderedPair => {
if (bounds[0] > orderedPair[0]) { bounds[0] = orderedPair[0] }
if (bounds[1] > orderedPair[1]) { bounds[1] = orderedPair[1] }
if (bounds[2] < orderedPair[0]) { bounds[2] = orderedPair[0] }
if (bounds[3] < orderedPair[1]) { bounds[3] = orderedPair[1] }
})
return bounds
}
const bounds = getBounds(points)
const center = getCenter(...bounds)
console.log('bounds', bounds)
console.log('center', center)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment