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.
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.
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:
Then we can just simply call this function in Fragment to get Place object:
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 APIPlacesClient.fetchPlace(request)
We convert the callback to Observable:
Then we can just simply call this function in Fragment to a list of predictions:
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.
That’s it, you can also check the complete codes on GitHub.