如何在不重复请求的情况下使用Google Places API获取某种类型的Lat Longs列表?

时间:2018-10-05 13:39:51

标签: java android kotlin location google-places-api

这是我的代码

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))
                }
            }
        }
    }

对于每家超市,只要自动完成预测中不包含此信息,它就不得不再次请求获取经纬度。

有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

就我所知,您无法保存两次调用,但是由于您要返回列表,因此可以使用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))
            }
        }
    }
}

答案 1 :(得分:0)

您可以尝试一下。效果很好。

  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()

希望它可以为您提供帮助。

相关问题