How to format GPS latitude and longitude?

后端 未结 7 822
囚心锁ツ
囚心锁ツ 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:16

    Here's a Kotlin version, adapted from Martin Weber's answer. It also sets the correct hemisphere; N, S, W or E

    object LocationConverter {
    
        fun latitudeAsDMS(latitude: Double, decimalPlace: Int): String {
            val direction = if (latitude > 0) "N" else "S"
            var strLatitude = Location.convert(latitude.absoluteValue, Location.FORMAT_SECONDS)
            strLatitude = replaceDelimiters(strLatitude, decimalPlace)
            strLatitude += " $direction"
            return strLatitude
        }
    
        fun longitudeAsDMS(longitude: Double, decimalPlace: Int): String {
            val direction = if (longitude > 0) "W" else "E"
            var strLongitude = Location.convert(longitude.absoluteValue, Location.FORMAT_SECONDS)
            strLongitude = replaceDelimiters(strLongitude, decimalPlace)
            strLongitude += " $direction"
            return strLongitude
        }
    
        private fun replaceDelimiters(str: String, decimalPlace: Int): String {
            var str = str
            str = str.replaceFirst(":".toRegex(), "°")
            str = str.replaceFirst(":".toRegex(), "'")
            val pointIndex = str.indexOf(".")
            val endIndex = pointIndex + 1 + decimalPlace
            if (endIndex < str.length) {
                str = str.substring(0, endIndex)
            }
            str += "\""
            return str
        }
    }
    

提交回复
热议问题