如何在没有双重请求的情况下使用 Google Places API 获取特定类型的 Lat Longs 列表?

How to get a list of Lat Longs of a certain type using Google Places API without double requesting?

这是我的代码

mGeoDataClient.getAutocompletePredictions("Supermarket", null, null).addOnSuccessListener {
        it.forEach {
            it.placeId?.let {
                mGeoDataClient.getPlaceById(it).addOnSuccessListener {
                    val marker = it[0].latLng
                    val name = it[0].name.toString()
                    mMap.addMarker(MarkerOptions().position(marker).title(name))
                }
            }
        }
    }

对于它发现的每家超市,它都必须再次请求获取纬度,因为自动完成预测中不包含此信息,只有地点 ID。

有更好的方法吗?

据我所知,您无法保存两次调用,但由于您要返回一个列表,您可以使用 getPlaceById(String...placeIds) 调用保存 n 次调用。

mGeoDataClient.getAutocompletePredictions("Supermarket", null, null).addOnSuccessListener {
    it.map{ it.placeId}.filterNotNull().toTypedArray().let {
        mGeoDataClient.getPlaceById(*it).addOnSuccessListener {
            it.forEach{
                val marker = it.latLng
                val name = it.name.toString()
                mMap.addMarker(MarkerOptions().position(marker).title(name))
            }
        }
    }
}

你可以试试这个。效果很好。

  mGeoDataClient?.getAutocompletePredictions("Supermarket", null, null)?.addOnSuccessListener{
        it.forEach { prediction ->
            val placeId = prediction.placeId
            val pendingResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient!!, placeId)
            pendingResult.setResultCallback {  placeBuffer->
                val place = placeBuffer.get(0)
                val marker = place.latLng
                val name = place.name.toString()
                mMap.addMarker(MarkerOptions().position(marker).title(name))
            }
        }
    }

这就是我的 mGoogleApiClient 初始化的方式:

  private var mGoogleApiClient: GoogleApiClient? = null

  mGoogleApiClient = GoogleApiClient.Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, this)
            .build()

希望对您有所帮助。