Skip to content

Instantly share code, notes, and snippets.

@umpteenthdev
Created May 6, 2019 10:22
Show Gist options
  • Select an option

  • Save umpteenthdev/adad46afab9d5a0855c2c6847bd5f25c to your computer and use it in GitHub Desktop.

Select an option

Save umpteenthdev/adad46afab9d5a0855c2c6847bd5f25c to your computer and use it in GitHub Desktop.
Convert decimal coordinates to degrees
import kotlin.math.absoluteValue
import kotlin.math.roundToInt
private const val NORTH = "N"
private const val SOUTH = "S"
private const val EAST = "E"
private const val WEST = "W"
fun convertDecimalToDegrees(lat: Double, lng: Double): String = "${convertLat(lat)} ${convertLng(lng)}"
private fun convertLat(lat: Double): String {
val direction = if (lat < 0) SOUTH else NORTH
return "${convertDecimalToDegrees(lat)}$direction"
}
private fun convertLng(lng: Double): String {
val direction = if (lng < 0) WEST else EAST
return "${convertDecimalToDegrees(lng)}$direction"
}
private fun convertDecimalToDegrees(number: Double): String {
var value = number.absoluteValue
val degrees = value.toInt()
value = (value - degrees) * 60
val minutes = value.toInt()
value = (value - minutes) * 60
val seconds = value.roundToInt()
return """$degrees°$minutes'$seconds""""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment