使用特定城市的谷歌地图 API 获取自动完成的地址

Posted

技术标签:

【中文标题】使用特定城市的谷歌地图 API 获取自动完成的地址【英文标题】:Fetch auto completed address using google map API for particular city 【发布时间】:2020-05-21 01:10:58 【问题描述】:

我正在构建一个 android 应用程序,我在其中使用谷歌地图 API 来获取位置。我已将限制设置为国家(印度)地址。有什么办法可以明智地为州(马哈拉施特拉邦)和城市(浦那)设置界限吗?

以下是我使用谷歌地图 API 密钥获取地址的代码

List < Place.Field > placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.TYPES);

FetchPlaceRequest request = null;
if (placeID != null) 
    request = FetchPlaceRequest.builder(placeID, placeFields)

        .build();


if (request != null) 
    placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener < FetchPlaceResponse > () 
        @SuppressLint("SetTextI18n")
        @Override
        public void onSuccess(FetchPlaceResponse task) 
            localityAddressEdt.setText(task.getPlace().getName() + "\n" + task.getPlace().getAddress());
            pinCode = "";
            latLng = task.getPlace().getLatLng();

        
    ).addOnFailureListener(new OnFailureListener() 
        @Override
        public void onFailure(@NonNull Exception e) 
            e.printStackTrace();
        
    );

 catch (Exception e) 
    e.printStackTrace();

以下是我的适配器代码(getAutocomplete 方法用于国家限制):

public class AutoCompleteAdapter extends ArrayAdapter < AutocompletePrediction > implements Filterable 

    private ArrayList < AutocompletePrediction > mResultList;
    private PlacesClient placesClient;

    public AutoCompleteAdapter(Context context, PlacesClient placesClient) 
        super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
        this.placesClient = placesClient;
    

    @Override
    public int getCount() 
        return mResultList.size();
    

    @Override
    public AutocompletePrediction getItem(int position) 
        return mResultList.get(position);
    

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) 
        View row = super.getView(position, convertView, parent);

        AutocompletePrediction item = getItem(position);

        TextView textView1 = row.findViewById(android.R.id.text1);
        TextView textView2 = row.findViewById(android.R.id.text2);
        if (item != null) 
            textView1.setText(item.getPrimaryText(null));
            textView2.setText(item.getSecondaryText(null));
        

        return row;
    

    @NonNull
    @Override
    public Filter getFilter() 
        return new Filter() 
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) 

                FilterResults results = new FilterResults();

                // We need a separate list to store the results, since
                // this is run asynchronously.
                ArrayList < AutocompletePrediction > filterData = new ArrayList < > ();

                // Skip the autocomplete query if no constraints are given.
                if (charSequence != null) 
                    // Query the autocomplete API for the (constraint) search string.
                    filterData = getAutocomplete(charSequence);
                

                results.values = filterData;
                if (filterData != null) 
                    results.count = filterData.size();
                 else 
                    results.count = 0;
                

                return results;
            

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence charSequence, FilterResults results) 

                if (results != null && results.count > 0) 
                    // The API returned at least one result, update the data.
                    mResultList = (ArrayList < AutocompletePrediction > ) results.values;
                    notifyDataSetChanged();
                 else 
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                
            

            @Override
            public CharSequence convertResultToString(Object resultValue) 
                // Override this method to display a readable result in the AutocompleteTextView
                // when clicked.
                if (resultValue instanceof AutocompletePrediction) 
                    return ((AutocompletePrediction) resultValue).getFullText(null);
                 else 
                    return super.convertResultToString(resultValue);
                
            
        ;
    

    private ArrayList < AutocompletePrediction > getAutocomplete(CharSequence constraint) 

        final FindAutocompletePredictionsRequest.Builder requestBuilder =
            FindAutocompletePredictionsRequest.builder()
            .setQuery(constraint.toString())
            .setCountry("IN")
            .setSessionToken(AutocompleteSessionToken.newInstance());


        Task < FindAutocompletePredictionsResponse > results =
            placesClient.findAutocompletePredictions(requestBuilder.build());


        //Wait to get results.
        try 
            Tasks.await(results, 60, TimeUnit.SECONDS);
         catch (ExecutionException | InterruptedException | TimeoutException e) 
            e.printStackTrace();
        

        if (results.isSuccessful()) 
            if (results.getResult() != null) 
                return (ArrayList < AutocompletePrediction > ) results.getResult().getAutocompletePredictions();
            
            return null;
         else 
            return null;
        
    

【问题讨论】:

嘿!你试过解决方案吗? 【参考方案1】:

FindAutocompletePredictionsRequest.Builder 有两个公共方法setLocationBias()setLocationRestriction() 可以帮助您获取特定城市的结果

setLocationBias() 将为您提供偏向于您的特定位置的结果。预测不一定在指定的位置内。仍然可以出现外部结果,但它们的优先级较低。

setLocationRestriction() 将对结果施加完全限制,并且只显示指定位置内的结果。

您可以在代码中使用它,例如

final FindAutocompletePredictionsRequest.Builder requestBuilder =
            FindAutocompletePredictionsRequest.builder()
                    .setQuery(constraint.toString())
                    .setCountry("IN")
                    .setLocationRestriction(getLocationRestriction())
                    .setSessionToken(AutocompleteSessionToken.newInstance());


    private LocationRestriction getLocationRestriction() 
        return getBounds();
      


    private RectangularBounds getBounds() 

        // south-west coordinate of your specific region
        LatLng southWestLatLang = new LatLng(26.889599, 75.743508);

        // north- east coordinate of your specific region
        LatLng northEastLatLang = new LatLng(26.945622, 75.849623);

        LatLngBounds bounds = new LatLngBounds(southWestLatLang, northEastLatLang);


        return RectangularBounds.newInstance(bounds);
    

如果你想了解更多关于LatLang Bound,可以查看文档here

额外:-here 你可以从 Google 找到一个非常好的地图 Git 存储库,其中包括地点自动完成的示例项目

【讨论】:

以上是关于使用特定城市的谷歌地图 API 获取自动完成的地址的主要内容,如果未能解决你的问题,请参考以下文章

使用带有 select2 的谷歌地图自动完成 api

带有多个标记的谷歌地图自动中心

谷歌地图自动完成:只输出地址,没有国家和城市

谷歌地理编码 API 不如使用地址的谷歌地图准确

如何解析特定的谷歌地图 API 网络服务 JSON 响应

在浏览器中打开带有特定地址的谷歌地图[关闭]