fun getAddressFromLocation(context: Context,latitude: Double, longitude: Double): String? { val geocoder = Geocoder(context, Locale.getDefault()) val addresses: List<Address>? var addressText = "" try { addresses = geocoder.getFromLocation(latitude, longitude, 1) if (addresses != null && addresses.isNotEmpty()) { val address = addresses[0] val sb = StringBuilder() for (i in 0..address.maxAddressLineIndex) { sb.append(address.getAddressLine(i)).append("\n") } addressText = sb.toString().trim() } } catch (e: IOException) { e.printStackTrace() } return addressText }这个代码如何只获取市
时间: 2024-02-14 20:29:50 浏览: 109
您可以在获取地址的循环中判断地址的类型,如果是市级地址,就只获取对应的部分即可。以下是修改后的代码示例:
```kotlin
fun getCityFromLocation(context: Context, latitude: Double, longitude: Double): String? {
val geocoder = Geocoder(context, Locale.getDefault())
val addresses: List<Address>?
var city = ""
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1)
if (addresses != null && addresses.isNotEmpty()) {
val address = addresses[0]
val sb = StringBuilder()
for (i in 0..address.maxAddressLineIndex) {
val addressLine = address.getAddressLine(i)
if (addressLine.contains("市")) {
city = addressLine
break
}
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return city
}
```
在上述代码中,我添加了一个判断,如果地址中包含"市"字,就将该地址赋值给city变量并跳出循环。这样就只获取了市级地址。注意,这里假设返回的地址列表中第一个地址就是最精确的地址,如果需要更多精确度,请根据实际情况进行调整。
阅读全文