Skip to content

Instantly share code, notes, and snippets.

@eugenebrusov
Created January 8, 2020 13:03
Show Gist options
  • Save eugenebrusov/caea832a14bec61ba2293fffe450673e to your computer and use it in GitHub Desktop.
Save eugenebrusov/caea832a14bec61ba2293fffe450673e to your computer and use it in GitHub Desktop.
fun findAutocompletePredictions(
lat: Double,
lng: Double,
query: String
): Single<List<AutocompletePrediction>> = Single
.create<RectangularBounds> { emitter ->
try {
val from = LatLng(lat, lng)
val distance = 20000.0
val southwestHeading = 225.0
val northeastHeading = 45.0
val southwestCorner =
SphericalUtil.computeOffset(from, distance, southwestHeading)
val northeastCorner =
SphericalUtil.computeOffset(from, distance, northeastHeading)
val bounds =
RectangularBounds.newInstance(southwestCorner, northeastCorner)
emitter.onSuccess(bounds)
} catch (e: Exception) {
emitter.tryOnError(GooglePlacesInvalidRequestException)
}
}.flatMap { bounds ->
Single.create<List<AutocompletePrediction>> { emitter ->
try {
val token = AutocompleteSessionToken.newInstance()
val cancellationToken = CancellationTokenSource()
val request = FindAutocompletePredictionsRequest.builder()
.setCountry("sa")
.setSessionToken(token)
.setQuery(query)
.setLocationBias(bounds)
.setCancellationToken(cancellationToken.token)
.build()
val client = Places.createClient(application)
client.findAutocompletePredictions(request)
.addOnSuccessListener { response ->
emitter.onSuccess(response.autocompletePredictions)
}
.addOnFailureListener { e ->
emitter.tryOnError(e)
}
emitter.setCancellable {
cancellationToken.cancel()
}
} catch (e: Exception) {
emitter.tryOnError(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment