Created
July 18, 2019 09:53
-
-
Save EmmanuelGuther/a1698096fbf9bcf56e4847b36d517893 to your computer and use it in GitHub Desktop.
Kotlin generate random location inside radius
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
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