我正在我的Android应用程序上实现Google的位置自动填充功能,并且该功能可以显示每个相似的位置,但是只有当用户尝试搜索任何内容时,我如何才能获得城市建议.
我搜索了很多我找不到AndroID地方自动完成的类似问题.
我已经从Google的示例中实现了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; } }}
我是初学者,所以如果您发现任何错误,请指出.那将是很大的帮助.
谢谢!
解决方法:
您可以使用Google的地方自动填充功能
Step 1:-
在Google Developers帐户中添加一个项目,然后从那里获取密钥
https://console.developers.google.com/flows/enableapi?apiid=appsactivity&credential=client_key&pli=1
范例程式码
Step 2:-
添加gradle
implementation 'com.Google.androID.gms:play-services-places:9.6.0'
或最新版本
implementation 'com.Google.androID.gms:play-services-places:latest_version'
Step 3:-
在清单文件中添加此标签
<Meta-data androID:name="com.Google.androID.geo.API_KEY" androID:value="Your API key"/>
Step 4:-
现在像这样用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/
谢谢
总结以上是内存溢出为你收集整理的android-Google Places API自动完成获取城市列表全部内容,希望文章能够帮你解决android-Google Places API自动完成获取城市列表所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)