关键词:
【中文标题】Google Places API Autocomplete 仅获取城市列表【英文标题】:Google Places API Autocomplete get cities List only 【发布时间】:2019-01-27 04:08:05 【问题描述】:我正在我的 Android 应用程序上实现 google 的地点自动完成功能,它可以显示每个类似的地点,但是只有当用户尝试搜索任何内容时,我才能获得城市建议。
我进行了很多搜索,但无法找到 Android 位置自动填充的类似问题。
我已经从谷歌的例子中实现了 PlaceAutocompleteAdapter,它看起来像这样
PlaceAutocompleteAdapter
package com.tribikram.smartcitytraveler;
import android.content.Context;
import android.graphics.Typeface;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.data.DataBufferUtils;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBufferResponse;
import com.google.android.gms.location.places.GeoDataClient;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.tasks.RuntimeExecutionException;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* Adapter that handles Autocomplete requests from the Places Geo Data Client.
* @link AutocompletePrediction results from the API are frozen and stored directly in this
* adapter. (See @link AutocompletePrediction#freeze().)
*/
public class PlaceAutocompleteAdapter
extends ArrayAdapter<AutocompletePrediction> implements Filterable
private static final String TAG = "PlaceACA";
private static final CharacterStyle STYLE_BOLD = new StyleSpan(Typeface.BOLD);
/**
* Current results returned by this adapter.
*/
private ArrayList<AutocompletePrediction> mResultList;
/**
* Handles autocomplete requests.
*/
private GeoDataClient mGeoDataClient;
/**
* 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 android.widget.ArrayAdapter#ArrayAdapter(android.content.Context, int)
*/
public PlaceAutocompleteAdapter(Context context, GeoDataClient geoDataClient,
LatLngBounds bounds, AutocompleteFilter filter)
super(context, android.R.layout.simple_expandable_list_item_2, android.R.id.text1);
mGeoDataClient = geoDataClient;
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()
return mResultList.size();
/**
* 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.getPrimaryText(STYLE_BOLD));
textView2.setText(item.getSecondaryText(STYLE_BOLD));
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();
// 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 (constraint != null)
// Query the autocomplete API for the (constraint) search string.
filterData = getAutocomplete(constraint);
results.values = filterData;
if (filterData != null)
results.count = filterData.size();
else
results.count = 0;
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.
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);
;
/**
* Submits an autocomplete query to the Places Geo Data Autocomplete API.
* Results are returned as frozen AutocompletePrediction objects, ready to be cached.
* 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 GeoDataClient#getAutocompletePredictions(String, LatLngBounds, AutocompleteFilter)
* @see AutocompletePrediction#freeze()
*/
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint)
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.
Task<AutocompletePredictionBufferResponse> results =
mGeoDataClient.getAutocompletePredictions(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.
try
Tasks.await(results, 60, TimeUnit.SECONDS);
catch (ExecutionException | InterruptedException | TimeoutException e)
e.printStackTrace();
try
AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();
Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
+ " predictions.");
// Freeze the results immutable representation that can be stored safely.
return DataBufferUtils.freezeAndClose(autocompletePredictions);
catch (RuntimeExecutionException e)
// If the query did not complete successfully return null
Toast.makeText(getContext(), "Error contacting API: " + e.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call", e);
return null;
我是初学者,如果发现有任何错误,请指出。那将是很大的帮助。 谢谢!
【问题讨论】:
【参考方案1】:您可以使用 google 的 Place Autocomplete
第 1 步:-
在谷歌开发者帐户中添加一个项目并从那里获取密钥 https://console.developers.google.com/flows/enableapi?apiid=appsactivity&credential=client_key&pli=1
示例代码
第 2 步:-
添加分级
implementation 'com.google.android.gms:play-services-places:9.6.0'
或最新版本
implementation 'com.google.android.gms:play-services-places:latest_version'
第 3 步:-
在清单文件中添加这个标签
<meta-data android:name="com.google.android.geo.API_KEY" android:value="Your api key"/>
第四步:-
现在像这样使用PlaceSelectionListener
实现您的片段或活动类
public class Fragment_Profile extends Fragment implements View.OnClickListener, PlaceSelectionListener
声明这个变量
private static final int REQUEST_SELECT_PLACE = 1000;
然后最后点击按钮调用这个
try
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
Intent intent = new PlaceAutocomplete.IntentBuilder
(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(typeFilter)
.build(getActivity());
startActivityForResult(intent, REQUEST_SELECT_PLACE);
catch (GooglePlayServicesRepairableException |
GooglePlayServicesNotAvailableException e)
e.printStackTrace();
这是您正在寻找的过滤器
AutocompleteFilter.TYPE_FILTER_CITIES
然后在被覆盖的方法中获取选中的值
@Override
public void onPlaceSelected(Place place)
Log.i("Selected", "Place Selected: " + place.getAddress());
您可以从这里查看文档 https://developers.google.com/places/android-sdk/autocomplete 和 http://codesfor.in/android-places-autocomplete-example/
谢谢
【讨论】:
谢谢你的回答,我回家时会实施。顺便说一句,谷歌不建议使用com.google.android.gms:play-services-places
对吧?
感谢它的工作:) 你是伟大的兄弟。很抱歉我之前的评论谷歌确实建议使用com.google.android.gms:play-services-places
我真的为你感到高兴,亲爱的,这很酷,不用担心,如果你只是说我从来没有遇到过任何问题,我认为这不会是一个问题 :)
感谢您和 +1 的精彩回答。
感谢 @SaWin 兄弟,感谢您的支持,干杯 :)【参考方案2】:
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.setTypeFilter(TypeFilter.ADDRESS)
.setTypeFilter(TypeFilter.CITIES)
.setCountry("IN")
.build(SelectDistanceActivity.this);
startActivityForResult(intent, Constant.AUTOCOMPLETE_REQUEST_CODE);
//if you want to get city for specific country then use this line
//setCountry("IN")
【讨论】:
请提供更多详细信息 不鼓励仅使用代码的答案。请简要说明您的答案如何解决问题,以及为什么它可能优于提供的其他答案。Android Google Places API,getAutocompletePredictions 返回状态“PLACES_API_ACCESS_NOT_CONFIGURED”
】AndroidGooglePlacesAPI,getAutocompletePredictions返回状态“PLACES_API_ACCESS_NOT_CONFIGURED”【英文标题】:AndroidGooglePlacesAPI,getAutocompletePredictionsreturnsstatus\'PLACES_API_ACCESS_NOT_CONFIGURED\'【发布时间】:2015-10-0515:06:58【问 查看详情
Google Places API 与 Google Geocode API
】GooglePlacesAPI与GoogleGeocodeAPI【英文标题】:GooglePlacesAPIvs.GoogleGeocodeAPI【发布时间】:2014-03-1823:36:01【问题描述】:我已经使用自动完成功能和GoogleGeocodingApi实现了GooglePlacesAPI。问题是结果似乎无法正常工作。有时从自动完成列... 查看详情
使用 google-places-api 的简单 html 页面的 ApiNotActivatedMapError
】使用google-places-api的简单html页面的ApiNotActivatedMapError【英文标题】:ApiNotActivatedMapErrorforsimplehtmlpageusinggoogle-places-api【发布时间】:2016-06-1212:42:16【问题描述】:我正在尝试创建一个包含google-places-api的简单html页面(稍后我想... 查看详情
Google Places API 结果与 Google 搜索不匹配
】GooglePlacesAPI结果与Google搜索不匹配【英文标题】:GooglePlacesAPIresultsdonotmatchGooglesearch【发布时间】:2014-10-2403:40:57【问题描述】:在我的数据中,我发现了许多类似以下的示例。如果您在Google上搜索“CheyneyUniversityPA”,您会得... 查看详情
从 Google Places API 获得超过 5 条评论
】从GooglePlacesAPI获得超过5条评论【英文标题】:Togetmorethan5reviewsfromgoogleplacesAPI【发布时间】:2017-01-0612:22:55【问题描述】:我正在做一个应用程序,我使用googleplacesAPI提取google评论。当我在“https://developers.google.com/maps/documentati... 查看详情
Google Places API 和 URL Shorter API
】GooglePlacesAPI和URLShorterAPI【英文标题】:GoogleplacesAPIandURLshortenerAPI【发布时间】:2018-11-2007:00:28【问题描述】:简介:我正在尝试使用googlePlacesAPI和URLShorterAPI创建一个网络应用程序。如果用户搜索某个地点,它会提取地点ID并... 查看详情
Google Maps Places API 不工作
】GoogleMapsPlacesAPI不工作【英文标题】:GooglemapsPlacesAPInotworking【发布时间】:2015-06-0520:28:29【问题描述】:packagecom.example.googlemapstestproject;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importj 查看详情
Google Places API 错误
】GooglePlacesAPI错误【英文标题】:GooglePlacesAPIerror【发布时间】:2012-03-0320:00:49【问题描述】:我正在尝试使用GooglePlacesAPI请求伦敦市中心半径1000米内的所有地点,所需的输出类型是XML。这是我使用JQuery的代码:<!DOCTYPEhtml>&... 查看详情
Google Places API 自动填充特定城市
】GooglePlacesAPI自动填充特定城市【英文标题】:GooglePlacesAPIautocompletespecificcity【发布时间】:2013-05-0705:06:29【问题描述】:我有一些关于googleplacesapiforandroid的问题。这是正在调用的请求:https://maps.googleapis.com/maps/api/place/autocomple... 查看详情
Google Places API 总是返回错误
】GooglePlacesAPI总是返回错误【英文标题】:GooglePlacesAPIalwaysreturnerror【发布时间】:2015-05-0504:55:35【问题描述】:我已在我的android应用程序中集成了GooglePlacesAPI。我已经阅读了api文档SeeHere。我已经为android激活了GooglePlacesApi并生... 查看详情
Google Places API,获取用户地址
】GooglePlacesAPI,获取用户地址【英文标题】:GoogleplacesAPI,getuseraddresses【发布时间】:2015-12-3023:53:11【问题描述】:我一直在努力使用GooglePlacesAPI,我需要使用AddressAPI。我使用autoComplete和placePickerAPI很好,但由于某种原因AddressAPI... 查看详情
如何从 Google Places API 获取地点描述
】如何从GooglePlacesAPI获取地点描述【英文标题】:HowtogetplacedescriptionfromGooglePlacesAPI【发布时间】:2018-01-2820:28:55【问题描述】:我正在尝试使用Google地点API来获取某些地点的信息。我有一个来自Google搜索的示例:这里是我想要... 查看详情
Google Places API 返回邮政编码
】GooglePlacesAPI返回邮政编码【英文标题】:GooglePlacesAPIReturnPostcode【发布时间】:2020-12-1318:05:55【问题描述】:我正在尝试获取返回的GooglePlacesAPI的邮政编码。我到处寻找,但似乎找不到人们如何做到这一点的有效示例。这是我... 查看详情
Google Places API 将预测转化为预测
】GooglePlacesAPI将预测转化为预测【英文标题】:GoogleplacesAPIturnpredictionsintoPrediction【发布时间】:2021-10-1805:50:58【问题描述】:我有这个代码来自动完成地址:finalrequest=\'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=$input&am... 查看详情
使用 Google Places API 获得 20 多个结果
】使用GooglePlacesAPI获得20多个结果【英文标题】:Obtainingmorethan20resultswithGooglePlacesAPI【发布时间】:2011-10-2109:43:48【问题描述】:我想开发一个地图应用程序,它会显示给定地点附近的银行。我使用Places库进行搜索,每次它只返... 查看详情
google Places 自动完成 api 适用于所有地方,但子域
】googlePlaces自动完成api适用于所有地方,但子域【英文标题】:googlePlacesautocompleteapiworkseverywherebutsubdomain【发布时间】:2016-09-2019:19:47【问题描述】:我遇到了GooglePlaces自动完成API的问题。https://developers.google.com/maps/documentation/ja... 查看详情
使用 Google PLACES Api 搜索查看自动完成建议
】使用GooglePLACESApi搜索查看自动完成建议【英文标题】:SearchViewAutocompletesuggestionsusingGooglePLACESApi【发布时间】:2020-07-0701:52:51【问题描述】:@OverridepublicbooleanonCreateOptionsMenu(Menumenu)super.onCreateOptionsMenu(menu);this.menu=menu;Me 查看详情
Google Places web api 不与 superagent 合作
】GooglePlaceswebapi不与superagent合作【英文标题】:GooglePlaceswebapinotcooperatingwithsuperagent【发布时间】:2018-02-1122:28:23【问题描述】:我正在尝试通过谷歌查询地点自动完成api,使用以下sn-prequest.get(`https://maps.googleapis.com/maps/api/place/a... 查看详情