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

July 22, 2018

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 bounds
val 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 type
val task = geoDataClient.getAutocompletePredictions(query, latLngBounds, null)

// I calling Tasks.await within kotlin coroutines / background thread
// Else, use task.addOnSuccessListener or task.addOnCompleteListener instead
val 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.