Skip to content

Instantly share code, notes, and snippets.

@utsmannn
Created June 24, 2020 10:45
Show Gist options
  • Save utsmannn/6d9364ebde4c3b4a64f78b03c7b78952 to your computer and use it in GitHub Desktop.
Save utsmannn/6d9364ebde4c3b4a64f78b03c7b78952 to your computer and use it in GitHub Desktop.
object MathUtil {
fun computeHeading(from: LatLng, to: LatLng): Double {
val fromLat = Math.toRadians(from.latitude)
val fromLng = Math.toRadians(from.longitude)
val toLat = Math.toRadians(to.latitude)
val toLng = Math.toRadians(to.longitude)
val dLng = toLng - fromLng
val heading = atan2(
sin(dLng) * cos(toLat),
cos(fromLat) * sin(toLat) - sin(fromLat) * cos(toLat) * cos(dLng)
)
return wrap(Math.toDegrees(heading))
}
private fun wrap(n: Double): Double {
val min = -180.0
val max = 180.0
return if (n >= min && n < max) n else mod(n - -180.0) + min
}
private fun mod(x: Double): Double {
val m = 360.0
return (x % m + m) % m
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment