Android Practice — Google Place Autocomplete & Search in Rx

Weiyi Li
3 min readSep 23, 2019

--

This article introduces search places with Places SDK in the following aspects: (1) two options to search place; (2) use Rx to break with the OnActivityResult and callback implementation; (3) use Rx to improve search performance.

Images from https://developers.google.com/maps/documentation/javascript/images/places-autocomplete-suggest.png

Google Place SDK provides 2 options to search place:

  • Launch built-in autocomplete activity by using an intent, that means you cannot customize the search UI.
  • Get place predictions programmatically which allows you to create a custom search UI.

Option 1: Launch built-in autocomplete activity

You can get the Place object on the onActivityResult callback, A Place encapsulates information about a physical location, including its name, full address, latLng, address components like street number, route, suburb/locality, country, postal code if available.

Normally the info is enough for UI displaying purpose and can also be used to fetch data from other servers.

Code snippet: Place fields structure

onActivityResult should be overridden to handle the result when the user has selected a place. However, we can use RxActivityResult which is a lib to break with the OnActivityResult implementation:

Code snippet: launch autocomplete activity in Rx

Then we can just simply call this function in Fragment to get Place object:

Code snippet: launch autocomplete activity sample

Option 2: Get place predictions programmatically

You can get a list of AutocompletePrediction objects from API PlacesClient.findAutocompletePredictions(request) callback, the object represents the predicted place, two fields of it are commonly used in practice:

  • getFullText(CharacterStyle) returns the full text of a place description, which can be used for UI displaying purpose.
  • getPlaceId() returns the place ID of the predicted place, which can be used to retrieve the Place object by calling API PlacesClient.fetchPlace(request)

We convert the callback to Observable:

Code snippet: Get place predictions in Rx

Then we can just simply call this function in Fragment to a list of predictions:

Code snippet: Get place predictions sample

Search

queryTextChanges is an extension function which returns a text changes observable, it utilizes the Rx operators include filter, debounce, distinctUntilChanged to improve search performance by avoiding duplicating API calls.

Code snippet: queryTextChanges

That’s it, you can also check the complete codes on GitHub.

Refer

--

--