Google Places API Autocomplete get cities List only

对着背影说爱祢 提交于 2019-12-03 21:16:46
Quick learner

You can use Place Autocomplete by google

Step 1:-

Add a project in google developers account and get the key from there https://console.developers.google.com/flows/enableapi?apiid=appsactivity&credential=client_key&pli=1

Example code

Step 2:-

Add gradle

 implementation 'com.google.android.gms:play-services-places:9.6.0'

or latest version

implementation 'com.google.android.gms:play-services-places:latest_version'

Step 3:-

add this tag in manifest file

<meta-data android:name="com.google.android.geo.API_KEY" android:value="Your api key"/>

Step 4:-

Now Implement your fragment or activity class with PlaceSelectionListener like this

public class Fragment_Profile extends Fragment implements View.OnClickListener, PlaceSelectionListener

declare this variable

private static final int REQUEST_SELECT_PLACE = 1000;

then finally on button click call this

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();
                }

This is the filter you are looking for

AutocompleteFilter.TYPE_FILTER_CITIES

then in the overridden method get the selected value

 @Override
    public void onPlaceSelected(Place place) {
        Log.i("Selected", "Place Selected: " + place.getAddress());

    }

You can check the documentation from here https://developers.google.com/places/android-sdk/autocomplete and http://codesfor.in/android-places-autocomplete-example/

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!