How to format GPS latitude and longitude?

后端 未结 7 897
囚心锁ツ
囚心锁ツ 2021-01-04 07:48

In android(java) when you get the current latitude and longitude using the function getlatitude() etc you get the coordinates in decimal format:

latit

7条回答
  •  盖世英雄少女心
    2021-01-04 08:30

    I wanted something similar and after studying answers here and Wikipedia, found there is a standard for formatting coordinates, ISO 6709#Annex D which describes the desired text representation for coordinates, considering that and wanting to have a portable and compact implementation in Kotlin, I ended with this code hopefully would be useful for others,

    import kotlin.math.abs
    import java.util.Locale
    
    // https://en.wikipedia.org/wiki/ISO_6709#Representation_at_the_human_interface_(Annex_D)
    fun formatCoordinateISO6709(lat: Double, long: Double, alt: Double? = null) = listOf(
        abs(lat) to if (lat >= 0) "N" else "S", abs(long) to if (long >= 0) "E" else "W"
    ).joinToString(" ") {
        val degrees = it.first.toInt()
        val minutes = ((it.first - degrees) * 60).toInt()
        val seconds = ((it.first - degrees) * 3600 % 60).toInt()
        "%d°%02d′%02d″%s".format(Locale.US, degrees, minutes, seconds, it.second)
    } + (alt?.let { " %s%.1fm".format(Locale.US, if (alt < 0) "−" else "", abs(alt)) } ?: "")
    

提交回复
热议问题