如何从谷歌地图地址获取“城市名称”?

时间:2020-12-29 20:40:00

标签: android kotlin retrofit google-maps-android-api-2

<块引用>

我只需要城市名称,因为我会在weatherapi中使用它。

<块引用>

但是在 Logd 出现之后,城市和县名总是放在一起。

<块引用>

2020-12-29 20:53:07.463 7093-7093/com.example.projekt1rain D/MapViewFragment:test5 马里通布图

那么我怎样才能得到 city ??

override fun onMapReady(map: GoogleMap?) {

        if (map != null) {
            nMap = map
        }

        map?.let {
            nMap = it

            nMap.setOnInfoWindowClickListener { markerToDelete ->
                Log.i(TAG, "onWindowsClickListener - Delete Thismarker")
                markers.remove(markerToDelete)
                markerToDelete.remove()
            }


            nMap.setOnMapLongClickListener { latlng ->

                Log.i(TAG, "onMapLongClickListener" + latlng)

                Toast.makeText(
                    requireContext(),
                    "this is toast message" + latlng,
                    Toast.LENGTH_SHORT
                ).show()
                showAlertDialog(latlng)

                // i need just city name cuz i will use it in weatherapi.
                // But after Logd coming always city and county name together.
                val address= getAddress(latlng.latitude, latlng.longitude)
                retrofitResponse(address)

                Log.d(TAG,"test5 $address")
                Toast.makeText(requireContext(),"test"+address,Toast.LENGTH_LONG).show()
            }
        }
    }


    private fun getAddress(lat: Double, lng: Double): String {
        val geocoder = Geocoder(requireContext())
        val list = geocoder.getFromLocation(lat, lng, 1)
        return list[0].getAddressLine(0)
        //val stateName: String = addresses[0].getAddressLine(1)
    }
´´´

接口 CallWeatherApi {

@GET("weather")
fun getWeather(@retrofit2.http.Query("q") cityname: String?,
               @retrofit2.http.Query("appid") apiKey: String?
):Call<CurrentWeatherResponse?>?

} '''

1 个答案:

答案 0 :(得分:0)

试试

list[0].getLocality();

如果您需要 address 中的任何其他内容,您可以查看 Android Address Class Doc