允许在 kotlin 中使用 tomtom 搜索 api

enable to use tomtom search api in kotlin

找了一个星期了,官方documentation一点都不清楚

正如那里提到的,代码

val searchServiceConnection = SearchServiceManager.createAndBind(context,
    searchServiceConnectionCallback)

应在应用程序中初始化搜索 API。但不清楚之后如何使用它。

我以正确的方式安装并初始化了 API :

Gradle:

//library required for search
implementation("com.tomtom.online:sdk-search:2.4264")



android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

AndroidManifest

<meta-data
            android:name="OnlineSearch.Key"
            android:value="your-tomtom-key" />

我假设您在 AndroidManifest.xml 文件中有一个正确的 API 密钥。综上所述,您可以通过三个步骤开始使用 TomTom Search API:

  1. 创建搜索API 对象:

    val searchApi = OnlineSearchApi.create(applicationContext)!!
    
  2. 创建搜索查询对象:

    val text = "Berlin"
    val searchQuery = FuzzySearchQueryBuilder.create(text).build()
    
  3. 调用搜索 API 并在侦听器中捕获结果:

    searchApi.search(searchQuery, object: FuzzySearchResultListener {
        override fun onSearchResult(response: FuzzySearchResponse?) {
            Toast.makeText(applicationContext, "results", Toast.LENGTH_SHORT).show()
        }
    
        override fun onSearchError(error: SearchError?) {
            Toast.makeText(applicationContext, "error", Toast.LENGTH_SHORT).show()
        }
    })
    

基于给定的答案,现在已弃用,这是新的等价物:

    private val searchApi = OnlineSearchApi.create(application, TOMTOM_API_KEY)

    val term = "Berlin"
    
    searchApi.search(FuzzySearchSpecification.Builder(term).build(), object : FuzzyOutcomeCallback {
                        override fun onError(error: SearchException) {
                            Log.e(TAG, "onError: ", error)
                        }
            
                        override fun onSuccess(fuzzyOutcome: FuzzyOutcome) {
                            for (fuzzyDetails in fuzzyOutcome.fuzzyDetailsList)
                                fuzzyDetails.apply { // process results (here we just print them)                               
                                  Log.d(TAG, "onSuccess: fuzzyDetails = $fuzzyDetails")
                                }
                              }
                            })