Tuesday, 31 May 2016

PlaceAutocompleteIntent and PlaceAutocompleteFragment Example Android



Step 1:

add in android app gradle:

compile 'com.google.android.gms:play-services-nearby:8.4.0
'compile 'com.google.android.gms:play-services-location:8.4.0'

First of all need to API key and Enable Google Place API to search and get place details. Add your API key to your app manifest ,need to replacing YOUR_API_KEY with your own API key:
<application>
  ...
  <meta-data
      android:name="com.google.android.geo.API_KEY"
      android:value="YOUR_API_KEY"/>
</application>

Step 2:

PlaceAutocompleteIntent Example


private final static int PLACE_AUTOCOMPLETE_REQUEST_CODE = 12;
LatLng latlong;

call this mehod where you want to get auto complete location:
callPlaceAutocompleteActivityIntent();



 private void callPlaceAutocompleteActivityIntent() {
        try {
            Intent intent =
      new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .build(this);
            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
//PLACE_AUTOCOMPLETE_REQUEST_CODE is integer for request code       
 } catch (GooglePlayServicesRepairableException | 
                   GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.        }

    }


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Place place = PlaceAutocomplete.getPlace(this, data);
            latlong = place.getLatLng();
            txtlocation.setText(place.getAddress().toString());
        } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
            Status status = PlaceAutocomplete.getStatus(this, data);
        } else if (requestCode == RESULT_CANCELED) {

        }
    }
}





PlaceAutocompleteFragment Example


<fragment
  android:id="@+id/place_autocomplete_fragment"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
  />


Java:
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);


AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
        .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS)
        .build();
autocompleteFragment.setFilter(typeFilter);

autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place.
        Log.i(TAG, "Place: " + place.getName());//get place details here
    }

    @Override
    public void onError(Status status) {
        // TODO: Handle the error.
        Log.i(TAG, "An error occurred: " + status);
    }
});

No comments:

Post a Comment