Skip to content

Instantly share code, notes, and snippets.

@anoopmaddasseri
Last active July 3, 2019 09:32
Show Gist options
  • Save anoopmaddasseri/58db697680b3b445e2866e251c6ba55a to your computer and use it in GitHub Desktop.
Save anoopmaddasseri/58db697680b3b445e2866e251c6ba55a to your computer and use it in GitHub Desktop.
Places autocomplete picker helper using the new Places SDK client
package xxx.xxx.xxx
/*
* @author Anoop M <[email protected]>
* @version 1
* @since 03 July 2019
*
*/
import android.app.Activity
import android.content.Intent
import androidx.core.content.ContextCompat
import com.google.android.gms.maps.model.LatLng
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.widget.Autocomplete
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode
import com.vguard.tez.R
import java.lang.ref.WeakReference
import java.util.*
class PlacePickerHelper(activity: Activity) {
private val mActivityWeakReference: WeakReference<Activity> = WeakReference(activity)
var name: String? = null
private set
var address: String? = null
private set
var phone: String? = null
private set
var latLng: LatLng? = null
private set
private var hasResult: Boolean = false
// BEGIN_INCLUDE(intent)
// Set the fields to specify which types of place data to return.
// Start the autocomplete intent.
// END_INCLUDE(intent)
val placePickerIntent: Intent
get() {
val activity = mActivityWeakReference.get()
if (!Places.isInitialized()) {
Places.initialize(activity!!, "YOUR_API_KEY")
}
val fields =
Arrays.asList(Place.Field.NAME, Place.Field.ADDRESS, Place.Field.PHONE_NUMBER, Place.Field.LAT_LNG)
val intent = Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields
).build(activity!!)
intent.putExtra("primary_color", ContextCompat.getColor(activity, R.color.colorPrimary))
intent.putExtra("primary_color_dark", ContextCompat.getColor(activity, R.color.colorPrimary))
return intent
}
fun parsePickedPlace(data: Intent) {
val activity = mActivityWeakReference.get() ?: return
// This result is from the PlacePicker dialog.
/* User has picked a place, extract data.
Data is extracted from the returned intent by retrieving a Place object from
the PlacePicker.
*/
val place = Autocomplete.getPlaceFromIntent(data)
/* A Place object contains details about that place, such as its name, address
and phone number. Extract the name, address, phone number, place ID and place types.
*/
name = place.name
address = place.address
phone = place.phoneNumber
latLng = place.latLng
setHasResult(true)
}
fun hasResult(): Boolean {
return hasResult
}
fun setHasResult(hasResult: Boolean) {
this.hasResult = hasResult
}
companion object {
val REQUEST_PLACE_PICKER = 200
private val TAG = PlacePickerHelper::class.java.simpleName
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment