DEV Community

Bogdan Alexandru Militaru
Bogdan Alexandru Militaru

Posted on • Originally published at whyboobo.com on

Generate hexagons in JS based on center coordinates and radius

How to generate hexagons in javascript based on the center point coordinates and radius length

function drawHexagon (centerPointLatitude, centerPointLongitude, radiusLength) {
  const radius = radiusLength / 6371

  const angle = 2 * Math.PI / 6 // 2PI (360 degree) divded by 6 points of the hexagon shape

  const hexagon = []
  for (var i = 0; i < 6; i++) {
    const longitude = centerPointLongitude + (radius * Math.cos(angle * i))
    const latitude = centerPointLatitude + (radius * Math.sin(angle * i))

    hexagon.push([longitude, latitude])
  }

  // close the polygon adding the initial point
  hexagon.push(hexagon[0])

  return hexagon
}

drawHexagon(44.4268, 26.1024, 10)

Enter fullscreen mode Exit fullscreen mode

Image credits Pixabay

Top comments (0)