首页 > 解决方案 > 显示异常的地方自动完成 api

问题描述

我正在使用 Places 自动完成 api,我面临的问题是,当我尝试通过键入搜索任何地方时,它显示错误为 ->

在此处输入图像描述

现在我的代码是

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val apiKey = getString(R.string.api_key)

        if (!Places.isInitialized()) {
            Places.initialize(
                applicationContext,
                apiKey
            )
        }

        val placesClient =
            Places.createClient(this)
        gmap.setOnClickListener {
            onSearchCalled();
            //startActivity(Intent(this, Gmap::class.java))
        }

    fun onSearchCalled() { // Set the fields to specify which types of place data to return.
        val fields: List<Place.Field> = Arrays.asList(
            Place.Field.ID,
            Place.Field.NAME,
            Place.Field.ADDRESS,
            Place.Field.LAT_LNG,
            Place.Field.ADDRESS_COMPONENTS
        )
        // Start the autocomplete intent.
        val intent = Autocomplete.IntentBuilder(
            AutocompleteActivityMode.FULLSCREEN, fields
        ).build(this)
        startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val place =
                    Autocomplete.getPlaceFromIntent(data!!)
                Log.i(
                    "aaaaa",
                    "Place: " + place.name + ", " + place.id
                )
            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) { // TODO: Handle the error.
                val status =
                    Autocomplete.getStatusFromIntent(data!!)
                Log.i("aaaa", status.statusMessage)
            } else if (resultCode == Activity.RESULT_CANCELED) { // The user canceled the operation.
            }
        }
    }

我相信我根据谷歌文档遵循了所有内容, 并且我还附加了清单和 build.gradle 依赖项

implementation 'com.google.android.libraries.places:places:2.1.0'
implementation 'com.google.android.gms:play-services-places:17.0.0'

标签: androidgoogle-mapskotlingoogle-places-apigoogleplacesautocomplete

解决方案


适用于 Android 的 Places SDK 的 Google Play 服务版本已于 2019 年 1 月弃用。因此,首先,从您的 build.gradle 依赖项中删除此行:

implementation 'com.google.android.gms:play-services-places:17.0.0'

其次,确保您的项目启用了计费功能,并且Places API也已启用。

我刚刚测试了您的代码(使用我的有效 API 密钥并删除了上述 gms 依赖项),并且 Place Autocomplete 对我来说完美运行。希望这可以帮助!


推荐阅读