简体   繁体   English

如何将Google Places自动完成结果限制为仅特定国家/地区?

[英]How to restrict Google places auto complete result to a specif country only?

I want to make a search box like Uber where user enters the address/location but I want autoComplete to predict addresses only in one country say India. 我想制作一个类似Uber的搜索框,在其中用户输入地址/位置,但我希望autoComplete仅预测印度这样一个国家/地区的地址。

Autocomplete Adaptar 自动完成适配器

ArrayAdapter<AutocompletePrediction> implements Filterable {


private static final String TAG = "PlaceAutoComAdapter";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
/**
 * Current results returned by this adapter.
 */
private ArrayList<AutocompletePrediction> mResultList;

/**
 * Handles autocomplete requests.
 */
private GoogleApiClient mGoogleApiClient;

/**
 * The bounds used for Places Geo Data autocomplete API requests.
 */
private LatLngBounds mBounds;

/**
 * The autocomplete filter used to restrict queries to a specific set of place types.
 */
private AutocompleteFilter mPlaceFilter;

/**
 * Initializes with a resource for text rows and autocomplete query bounds.
 *
 * @see ArrayAdapter#ArrayAdapter(Context, int)
 */
public PlaceAutocompleteAdapter(Context context, GoogleApiClient googleApiClient,
                                LatLngBounds bounds, AutocompleteFilter filter) {
    super(context, android.R.layout.simple_list_item_1,android.R.id.text1);
    mGoogleApiClient = googleApiClient;
    mBounds = bounds;
    mPlaceFilter = filter;
}

/**
 * Sets the bounds for all subsequent queries.
 */
public void setBounds(LatLngBounds bounds) {

    mBounds = bounds;
}

/**
 * Returns the number of results received in the last autocomplete query.
 */
@Override
public int getCount() {
    if (mResultList!=null)
    return mResultList.size();
    else
        return 0;
}

/**
 * Returns an item from the last autocomplete query.
 */
@Override
public AutocompletePrediction getItem(int position) {
    return mResultList.get(position);
}

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

    // Sets the primary and secondary text for a row.
    // Note that getPrimaryText() and getSecondaryText() return a CharSequence that may contain
    // styling based on the given CharacterStyle.

    AutocompletePrediction item = getItem(position);

    TextView textView1 = (TextView) row.findViewById(android.R.id.text1);
    //TextView textView2 = (TextView) row.findViewById(android.R.id.text2);
    textView1.setText(item.getDescription());
    textView1.setTag(item);
    //textView2.setText(item.getDescription());

    return row;
}

/**
 * Returns the filter for the current set of autocomplete results.
 */
@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            // Skip the autocomplete query if no constraints are given.
            if (constraint != null) {
                // Query the autocomplete API for the (constraint) search string.
                mResultList = getAutocomplete(constraint);
                if (mResultList != null) {
                    // The API successfully returned results.
                    results.values = mResultList;
                    results.count = mResultList.size();
                }
            }
            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            if (results != null && results.count > 0) {
                // The API returned at least one result, update the data.
                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).getDescription();
            } else {
                return super.convertResultToString(resultValue);
            }
        }
    };
}

/**
 * Submits an autocomplete query to the Places Geo Data Autocomplete API.
 * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
 * objects to store the Place ID and description that the API returns.
 * Returns an empty list if no results were found.
 * Returns null if the API client is not available or the query did not complete
 * successfully.
 * This method MUST be called off the main UI thread, as it will block until data is returned
 * from the API, which may include a network request.
 *
 * @param constraint Autocomplete query string
 * @return Results from the autocomplete API or null if the query was not successful.
 * @see Places#GEO_DATA_API#getAutocomplete(CharSequence)
 * @see AutocompletePrediction#freeze()
 */
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG, "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
           /* Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();*/
            Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
            autocompletePredictions.release();
            return null;
        }

        Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                + " predictions.");

        // Freeze the results immutable representation that can be stored safely.
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    Log.e(TAG, "Google API client is not connected for autocomplete query.");
    return null;
}

}

设置过滤器并将其用作自动完成查询的一部分

filter.country = "In"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何限制谷歌地方自动填充到特定国家/地区? - how to restrict google places autocomplete to specific country? Android - Google Places API 自动完成 sdk,如何只获得英文结果? - Android - Google Places API auto complete sdk, How get results in only English? 如何在Android应用程序中使用Google的自动完成放置api - How to use Google's auto complete places api in Android application 在 Google Places Android API 中将自动完成搜索限制为特定国家/地区 - Restrict Autocomplete search to a particular country in Google Places Android API 如何限制Google自动填充功能仅搜索城市中的少数几个街区? - How to restrict google auto completion to search only a few neibourghoods in a city? 如何通过特定区域类型(国家/地区,子网站等)在Google Places API for Android中获取搜索自动填充功能? - How to get search autocomplete in Google Places API for Android only by specific region type (country, sublocality etc.)? 如何使用google maps api for android将地图限制为只有一个国家/地区 - how to restrict maps to only one country using google maps api for android Google Places Api,放置自动完成的mBound查询 - Google Places Api, Place auto-complete mBound Query 地方资讯自动完成功能会开启新的Google搜寻重叠式广告 - Places auto complete is opening a new overlay google search Google Places 自动完成 React 原生自定义视图 - Google Places Auto complete React native custom view
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM