目录

自动补全

概览

根据输入的关键字返回预测的输入关键字和地点查询建议。

使用约束

最多返回5条记录。

实现步骤

  1. 声明SearchService对象,并通过SearchServiceFactory创建SearchService实例。

    创建SearchService实例需要传入Context类型参数和API密钥。Context参数建议传入Activity类型,否则需要升级HMS Core(APK)时不会弹出升级界面。API密钥是您在华为开发者联盟创建应用时生成的API密钥,注意使用时需要调用URLEncoder.encode("Your apiKey", "UTF-8")方法对API密钥进行encodeURI编码。

  2. 构建QueryAutocompleteRequest对象,它是自动补全的请求体。其中query是必选参数,其余可选:

    • query:搜索关键字。
    • location:搜索结果偏向的经纬度。
    • radius:搜索半径,单位:米。取值范围:[1, 50000],默认50000米。该参数只用于优先显示结果,而非将结果限制在该搜索半径内。
    • language:搜索结果的语种,取值范围参见支持的语言的语种代码。如果不指定语种,返回英语,如果没有英语,返回当地语言。
    • politicalView:政治观点参数,采用ISO 3166-1 alpha-2规范的2位国家/地区码,该参数已废弃。
    • children:是否返回子节点,默认为false。传入children为true,返回子节点的siteId。

  3. 创建SearchResultListener对象,该对象用来侦听搜索结果。
  4. 通过第1步创建的SearchService对象调用queryAutocomplete()接口,传入第2步创建的QueryAutocompleteRequest对象和第3步创建的SearchResultListener对象。
  5. 通过第3步创建的SearchResultListener对象获取搜索结果QueryAutocompleteResponse对象。通过QueryAutocompleteResponse对象,可以获得预测输入的关键字和查询建议。
示例代码如下:
“Java”
// 声明SearchService对象 
private SearchService searchService; 
// 创建SearchService实例 
searchService = SearchServiceFactory.create(this, "API key"); 
// 创建请求体 
QueryAutocompleteRequest request = new QueryAutocompleteRequest(); 
request.setQuery("Paris"); 
Coordinate location = new Coordinate(48.893478, 2.334595); 
request.setLocation(location); 
request.setRadius(1000); 
request.setChildren(false);

// 创建搜索结果侦听器 
SearchResultListener<QueryAutocompleteResponse> resultListener =
	new SearchResultListener<QueryAutocompleteResponse>() {
                // 正常结果返回 
		@Override
		public void onSearchResult(QueryAutocompleteResponse results) {
			StringBuilder stringBuilder = new StringBuilder();
			if (results != null) {
				Site[] sites = results.getSites();
				if (sites != null && sites.length > 0) {
					int count = 1;
					for (Site site : sites) {
						AddressDetail addressDetail = site.getAddress();
						Coordinate location = site.getLocation();
						Poi poi = site.getPoi();
						CoordinateBounds viewport = site.getViewport();

						stringBuilder.append(String.format(
							"[%s] siteId: '%s', name: %s, formatAddress: %s, country: %s, countryCode: %s, location: %s, distance: %s, poiTypes: %s, viewport is %s, streetNumber: %s, postalCode: %s , tertiaryAdminArea: %s \n\n",
							"" + (count++), site.getSiteId(), site.getName(), site.getFormatAddress(),
							(addressDetail == null ? "" : addressDetail.getCountry()),
							(addressDetail == null ? "" : addressDetail.getCountryCode()),
							(location == null ? "" : (location.getLat() + "," + location.getLng())),
							site.getDistance(), (poi == null ? "" : Arrays.toString(poi.getPoiTypes())),
							(viewport == null ? "" : viewport.getNortheast() + "," + viewport.getSouthwest()),
							(addressDetail == null ? "" : addressDetail.getStreetNumber()),
							(addressDetail == null ? "" : addressDetail.getPostalCode()),
							(addressDetail == null ? "" : addressDetail.getTertiaryAdminArea())));
					}
				} else {
					stringBuilder.append("sites 0 results\n");
				}

				AutoCompletePrediction[] predictions = results.getPredictions();
				if (predictions != null && predictions.length > 0) {
					int count = 1;
					for (AutoCompletePrediction mPrediction : predictions) {
						stringBuilder.append(String.format("[%s] Prediction,description = %s ,", "" + (count++),
							mPrediction.getDescription()));

						Word[] matchedKeywords = mPrediction.getMatchedKeywords();
                                                if (matchedKeywords != null) {
						        for (Word matchedKeyword : matchedKeywords) {
							        stringBuilder.append("matchedKeywords: " + matchedKeyword.toString());
						        }
                                                }

						Word[] matchedWords = mPrediction.getMatchedWords();
                                                if (matchedWords != null) {
						        for (Word matchedWord : matchedWords) {
							        stringBuilder.append(",matchedWords: " + matchedWord.toString());
						        }
                                                }

						stringBuilder.append("\n");
					}
				} else {
					stringBuilder.append("Predictions 0 results");
				}
			}
			Log.d("TAG", stringBuilder.toString());
		}

                // 异常结果返回
		@Override
		public void onSearchError(SearchStatus status) {
			Log.i("TAG", "Error : " + status.getErrorCode() + " " + status.getErrorMessage());
		}
	};
// 调用自动补全接口
searchService.queryAutocomplete(request, resultListener);
“Kotlin”
// 声明SearchService对象
val searchService: SearchService
// 创建SearchService实例
searchService = SearchServiceFactory.create(this, "API key")
// 创建请求体
val request = QueryAutocompleteRequest()
request.query = "Paris"
val location = Coordinate(48.893478, 2.334595)
request.location = location
request.radius = 1000
// 创建搜索结果侦听器
val resultListener: SearchResultListener<QueryAutocompleteResponse> = object : SearchResultListener<QueryAutocompleteResponse> {
    // 正常结果返回
    override fun onSearchResult(results: QueryAutocompleteResponse?) {
        val stringBuilder = StringBuilder()
        if (results != null) {
            val sites = results.getSites()
            if (sites != null && sites.isNotEmpty()) {
                var addressDetail: AddressDetail?
                var location: Coordinate?
                var poi: Poi?
                var viewport: CoordinateBounds?
                sites.forEachIndexed { index, site ->
                    addressDetail = site.getAddress()
                    location = site.getLocation()
                    poi = site.getPoi()
                    viewport = site.getViewport()
                    stringBuilder.append("[${index + 1}] siteId: ${site.getSiteId()}, name: ${site.getName()}, formatAddress: ${site.getFormatAddress()}" +
                            ", country: ${addressDetail?.getCountry() ?: ""}" +
                            ", countryCode: ${addressDetail?.getCountryCode() ?: ""}" +
                            ", location: ${if (location == null) "" else location?.getLat().toString() + "," + location?.getLng().toString()}" +
                            ", distance: ${site.getDistance()}" +
                            ", poiTypes: ${Arrays.toString(poi?.getPoiTypes())}" +
                            ", viewport: ${if (viewport == null) "" else viewport?.getNortheast().toString() + "," + viewport?.getSouthwest().toString()}" +
                            ", streetNumber: ${addressDetail?.getStreetNumber() ?: ""}" +
                            ", postalCode: ${addressDetail?.getPostalCode() ?: ""}" +
                            ", tertiaryAdminArea: ${addressDetail?.getTertiaryAdminArea() ?: ""} \n\n")
                }
            } else {
                stringBuilder.append("sites 0 results\n")
            }
            val predictions = results.getPredictions()
            if (predictions != null && predictions.isNotEmpty()) {
                predictions.forEachIndexed { index, autoCompletePrediction ->
                    stringBuilder.append("[${index + 1}] Prediction,description = ${autoCompletePrediction.getDescription()} ,")
                    val matchedKeywords = autoCompletePrediction.getMatchedKeywords()
                    for (matchedKeyword in matchedKeywords) {
                        stringBuilder.append("matchedKeywords: $matchedKeyword")
                    }
                    val matchedWords = autoCompletePrediction.getMatchedWords()
                    for (matchedWord in matchedWords) {
                        stringBuilder.append(",matchedWords: $matchedWord")
                    }
                    stringBuilder.append("\n")
                }
            } else {
                stringBuilder.append("Predictions 0 results")
            }
        }
        Log.d("zwxTAG", stringBuilder.toString())
    }
    // 异常结果返回
    override fun onSearchError(status: SearchStatus) {
        Log.i("TAG", "Error : ${status.getErrorCode()}  ${status.getErrorMessage()}")
    }
}
// 调用自动补全接口
searchService.queryAutocomplete(request, resultListener)