Android Google Places Find Nearby Places Using Autocomplete API (Programmatically)

The autocomplete service in the Places SDK for Android returns place predictions in response to user search queries. As the user types, the autocomplete service returns suggestions for places such as businesses, addresses and points of interest.

You can add autocomplete feature to your app by using widget (Fragment or Activity Intent) or programmatically. This article shall focus on programmatically.

Setup Google Play Services and add your API key by refering to Android Google Places Get Nearby Places (Google Play 15) or Google Android Map or Get Started.

val query = "search something"// convert location to 10m boundsval latLngBounds = location.toLatLng().toBounds(10.0)val geoDataClient = Places.getGeoDataClient(context)// query - text typed by user// LatLngBounds - biased results to this area// AutocompleteFilter - filter by place typeval task = geoDataClient.getAutocompletePredictions(query, latLngBounds, null)// I calling Tasks.await within kotlin coroutines / background thread// Else, use task.addOnSuccessListener or task.addOnCompleteListener insteadval result = Tasks.await(task)val ids = mutableListOf<String>()for (autocompletePrediction in result) {    // autocompletePrediction.placeId, getPrimaryText(null), getPlaceTypes(), etc    // sadly, you don't get address, location; additional API call is required    ids.add(autocompletePrediction.placeId)}fetchPlaces(ids)

NOTE: Refer to Android Get Current Location

NOTE: Refer to LatLng to Bounds by Radius for toBounds

To get more detail about the places returned by autocomplete.

fun fetchPlaces(ids: List<String>) {    val ids = items.map {        it.id    }    val task = geoDataClient.getPlaceById(*ids.toTypedArray())    val result = Tasks.await(task)    for (place in result) {        // place.id, name, address, placeTypes, latlng    }}

NOTE: take note of attribution requirement and usage limits.

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.