如何以编程方式实现谷歌地点自动完成并使用 kotlin 获取 latlng?

问题描述

我得到了地址,但没有得到纬度

package shweta.com.googleplacesautocomplete

import android.util.Log
import android.webkit.WebStorage
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.tasks.Tasks
import com.google.android.libraries.places.api.model.AutocompletePrediction
import com.google.android.libraries.places.api.model.AutocompleteSessionToken
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.model.TypeFilter
import com.google.android.libraries.places.api.net.FetchPlaceRequest
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest
import com.google.android.libraries.places.api.net.PlacesClient
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException

const val TASK_AWAIT = 120L
const val MAP_CAMERA_ZOOM = 11f
const val MAP_CAMERA_ZOOM_INT = 11

/**
 * This fun is used to move map
 * @receiver GoogleMap
 * @param latLng LatLng?
 */
fun GoogleMap.moveCameraOnMap(latLng: LatLng?) {
    this.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,MAP_CAMERA_ZOOM))
}

/**
 * This fun is used to move map
 * @receiver GoogleMap
 * @param latLng LatLng?
 */
fun GoogleMap.moveCameraOnMapBound(latLng: LatLngBounds?) {
    this.animateCamera(CameraUpdateFactory.newLatLngBounds(latLng,MAP_CAMERA_ZOOM_INT))
}

/**
 * This fun is used to get auto complete fields
 * @param mGeoDataClient GeoDataClient
 * @param constraint CharSequence
 * @return ArrayList<AutocompletePrediction>?
 */
fun getAutocomplete(mPlacesClient: PlacesClient,constraint: CharSequence): List<AutocompletePrediction> {
    var list = listof<AutocompletePrediction>()
    val token = AutocompleteSessionToken.newInstance()

    val fields = listof(Place.Field.ID,Place.Field.NAME,Place.Field.ADDRESS,Place.Field.LAT_LNG,Place.Field.ADDRESS_COMPONENTS,Place.Field.TYPES)

    val request = FindAutocompletePredictionsRequest
        .builder()
        .setTypeFilter(TypeFilter.ADDRESS)
        .setCountry("CL")
        .setSessionToken(token)
        .setQuery(constraint.toString())
        .build()

    val prediction = mPlacesClient.findAutocompletePredictions(request)
    
    try {
        Tasks.await(prediction,TASK_AWAIT,TimeUnit.SECONDS)
    } catch (e: ExecutionException) {
        e.printstacktrace()
    } catch (e: InterruptedException) {
        e.printstacktrace()
    } catch (e: TimeoutException) {
        e.printstacktrace()
    }

    if (prediction.isSuccessful) {
        val findAutocompletePredictionsResponse = prediction.result
        findAutocompletePredictionsResponse?.let {
            list = findAutocompletePredictionsResponse.autocompletePredictions
        }
        return list
    }
    return list
}

基于How to implement google places autocomplete programmatically代码

https://github.com/ShwetaChauhan18/GooglePlacesAutoComplete

我尝试按照以下链接中的教程进行操作:https://www.youtube.com/watch?v=6Trdd9EnmqY&list=PLgCYzUzKIBE-vInwQhGSdnbyJ62nixHCt&index=8。最近其中使用的一些方法已被弃用,因此我查看了 https://developers.google.com/places/android-sdk/autocomplete 上的文档,尤其是“以编程方式获取地点预测”和“迁移到新地点 SDK 客户端”。但是我一直无法获取kotli中的所有位置

解决方法

通过选择的预测来查询更多细节,如下所示。

fun fetchPlace(prediction: AutocompletePrediction) {

    // Specify the fields to return.
    val placeFields = listOf(Place.Field.ID,Place.Field.ADDRESS,Place.Field.LAT_LNG)
    val request = FetchPlaceRequest.newInstance(prediction.placeId,placeFields)

    // Use same PlacesClient instance used to fetch predictions
    placesClient.fetchPlace(request).addOnSuccessListener { response: FetchPlaceResponse ->
        response.place.latLng?.let {
            // lat lng details
        }
    }.addOnFailureListener { exception: Exception ->
        if (exception is ApiException) {
            val statusCode = exception.statusCode
        }
    }
}