Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save EmmanuelGuther/a1698096fbf9bcf56e4847b36d517893 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/a1698096fbf9bcf56e4847b36d517893 to your computer and use it in GitHub Desktop.
Kotlin generate random location inside radius
fun generateRandomLocationInsideRadius(x0: Double, y0: Double, radius: Int): LatLng {
val random = Random()
// Convert radius from meters to degrees
val radiusInDegrees = (radius / 111000f).toDouble()
val u = random.nextDouble()
val v = random.nextDouble()
val w = radiusInDegrees * sqrt(u)
val t = 2.0 * Math.PI * v
val x = w * cos(t)
val y = w * sin(t)
// Adjust the x-coordinate for the shrinking of the east-west distances
val newX = x / cos(Math.toRadians(y0))
val foundLongitude = newX + x0
val foundLatitude = y + y0
return LatLng(foundLongitude, foundLatitude)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment