Created
September 10, 2016 12:54
-
-
Save ccjeng/be9d384e0cd5e14ee682dac9d10a462b to your computer and use it in GitHub Desktop.
Google Places Autocomplete API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private PlaceAutocompleteAdapter adapter; | |
private AutoCompleteTextView autocompleteView; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
buildGoogleApiClient(); | |
autocompleteView = (AutoCompleteTextView)findViewById(R.id.autocomplete); | |
autocompleteView.setOnItemClickListener(autocompleteClickListener); | |
//設定篩選條件 | |
AutocompleteFilter filter = new AutocompleteFilter.Builder() | |
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES) | |
.build(); | |
adapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1, googleApiClient, null, filter); | |
autocompleteView.setAdapter(adapter); | |
} | |
private AdapterView.OnItemClickListener autocompleteClickListener = new AdapterView.OnItemClickListener() { | |
@Override | |
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { | |
final PlaceAutocompleteAdapter.PlaceAutocomplete item = mToAdapter.getItem(position); | |
final String placeId = String.valueOf(item.placeId); | |
Log.i(TAG, "Autocomplete item selected: " + item.description); | |
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi | |
.getPlaceById(mGoogleApiClient, placeId); | |
placeResult.setResultCallback(mToUpdatePlaceDetailsCallback); | |
Log.i(TAG, "Called getPlaceById to get Place details for " + item.placeId); | |
} | |
}; | |
private ResultCallback<PlaceBuffer> updatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() { | |
@Override | |
public void onResult(PlaceBuffer places) { | |
if (!places.getStatus().isSuccess()) { | |
// Request did not complete successfully | |
Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString()); | |
places.release(); | |
return; | |
} | |
places.release(); | |
} | |
}; | |
protected synchronized void buildGoogleApiClient() { | |
googleApiClient = new GoogleApiClient.Builder(this) | |
.addConnectionCallbacks(this) | |
.addOnConnectionFailedListener(this) | |
.addApi(Places.GEO_DATA_API) | |
.build(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment