Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add samples for release 3.1.0 #519

Merged
merged 16 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion demo-kotlin/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
<activity android:name=".CurrentPlaceActivity" />
<activity android:name=".PlaceIsOpenActivity" />
<activity
android:name=".programmatic_autocomplete.ProgrammaticAutocompleteToolbarActivity"
android:name=".programmatic_autocomplete.ProgrammaticAutocompleteGeocodingActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

</application>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import android.widget.Button
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import com.example.placesdemo.programmatic_autocomplete.ProgrammaticAutocompleteToolbarActivity
import com.example.placesdemo.programmatic_autocomplete.ProgrammaticAutocompleteGeocodingActivity
import com.google.android.libraries.places.api.Places

class MainActivity : AppCompatActivity() {
Expand All @@ -43,7 +43,7 @@ class MainActivity : AppCompatActivity() {

setLaunchActivityClickListener(R.id.autocomplete_button, PlaceAutocompleteActivity::class.java)
setLaunchActivityClickListener(R.id.autocomplete_address_button, AutocompleteAddressActivity::class.java)
setLaunchActivityClickListener(R.id.programmatic_autocomplete_button, ProgrammaticAutocompleteToolbarActivity::class.java)
setLaunchActivityClickListener(R.id.programmatic_autocomplete_button, ProgrammaticAutocompleteGeocodingActivity::class.java)
setLaunchActivityClickListener(R.id.current_place_button, CurrentPlaceActivity::class.java)
setLaunchActivityClickListener(R.id.place_and_photo_button, PlaceDetailsAndPhotosActivity::class.java)
setLaunchActivityClickListener(R.id.is_open_button, PlaceIsOpenActivity::class.java)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ class PlaceAutocompleteActivity : AppCompatActivity() {
/**
* Launches Autocomplete activity and handles result
*/
var autocompleteLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
private var autocompleteLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result ->
when (result.resultCode) {
AutocompleteActivity.RESULT_OK -> {
Expand Down Expand Up @@ -287,8 +287,4 @@ class PlaceAutocompleteActivity : AppCompatActivity() {
.setMessage(messageResId)
.show()
}

companion object {
private const val AUTOCOMPLETE_REQUEST_CODE = 23487
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ class PlaceIsOpenActivity : AppCompatActivity() {
* Requires a Place object that includes Place.Field.ID
*/
@SuppressLint("SetTextI18n")
private fun isOpenByPlaceObject(place: Place?) {
private fun isOpenByPlaceObject(place: Place) {
clearViews()
dismissKeyboard(binding.editTextPlaceId)
setLoading(true)
Expand All @@ -129,13 +129,10 @@ class PlaceIsOpenActivity : AppCompatActivity() {
val placeTask: Task<IsOpenResponse> = placesClient.isOpen(request)
placeTask.addOnSuccessListener { response ->
binding.textViewResponse.text =
"Is place open? " + response.isOpen + "\nExtra place details: \n" + place?.let {
stringify(
it
)
}
"Is place open? " + response.isOpen + "\nExtra place details: \n" + stringify(place)
wangela marked this conversation as resolved.
Show resolved Hide resolved
}
placeTask.addOnFailureListener { exception ->
placeTask.addOnFailureListener {
exception ->
exception.printStackTrace()
binding.textViewResponse.text = exception.message
}
Expand Down Expand Up @@ -172,8 +169,8 @@ class PlaceIsOpenActivity : AppCompatActivity() {
}

//////////////////////////
// Helper methods below //
//////////////////////////
// Helper methods below //
//////////////////////////
private fun dismissKeyboard(focusedEditText: EditText) {
val imm: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package com.example.placesdemo.programmatic_autocomplete

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Menu
import android.view.MenuItem
Expand All @@ -32,7 +33,6 @@ import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.example.placesdemo.BuildConfig
import com.example.placesdemo.MainActivity
import com.example.placesdemo.R
import com.example.placesdemo.model.GeocodingResult
import com.google.android.gms.common.api.ApiException
Expand All @@ -41,8 +41,10 @@ import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.AutocompletePrediction
import com.google.android.libraries.places.api.model.AutocompleteSessionToken
import com.google.android.libraries.places.api.model.LocationBias
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.model.RectangularBounds
import com.google.android.libraries.places.api.model.TypeFilter
import com.google.android.libraries.places.api.net.FetchPlaceRequest
import com.google.android.libraries.places.api.net.FetchPlaceResponse
import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.gson.GsonBuilder
Expand All @@ -52,13 +54,13 @@ import org.json.JSONException
/**
* An Activity that demonstrates programmatic as-you-type place predictions. The parameters of the
* request are currently hard coded in this Activity, to modify these parameters (e.g. location
* bias, place types, etc.), see [ProgrammaticAutocompleteToolbarActivity.getPlacePredictions]
* bias, place types, etc.), see [ProgrammaticAutocompleteGeocodingActivity.getPlacePredictions]
*
* @see https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically
*/
class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() {
class ProgrammaticAutocompleteGeocodingActivity : AppCompatActivity() {

private val handler = Handler()
private val handler = Handler(Looper.getMainLooper())
private val adapter = PlacePredictionAdapter()
private val gson = GsonBuilder().registerTypeAdapter(LatLng::class.java, LatLngAdapter()).create()

Expand Down Expand Up @@ -128,7 +130,10 @@ class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() {
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
recyclerView.addItemDecoration(DividerItemDecoration(this, layoutManager.orientation))
// Get just the location of the place using the Geocoding API
adapter.onPlaceClickListener = { geocodePlaceAndDisplay(it) }
// Alternative: Get more details about the place using Place Details
// adapter.onPlaceClickListener = { fetchPlaceAndDisplay(it) }
}

/**
Expand All @@ -148,32 +153,34 @@ class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() {
)

// Create a new programmatic Place Autocomplete request in Places SDK for Android
val newRequest = FindAutocompletePredictionsRequest
.builder()
.setSessionToken(sessionToken)
val newRequest = FindAutocompletePredictionsRequest.builder()
.setLocationBias(bias)
.setTypeFilter(TypeFilter.ESTABLISHMENT)
.setQuery(query)
.setCountries("IN")
.setTypesFilter(listOf("establishment")) // https://issuetracker.google.com/issues/261035620
// .setTypesFilter(listOf(TypeFilter.ESTABLISHMENT.toString()))
// Session Token only used to link related Place Details call. See https://goo.gle/paaln
.setSessionToken(sessionToken)
.setQuery(query)
.build()

// Perform autocomplete predictions request
placesClient.findAutocompletePredictions(newRequest).addOnSuccessListener { response ->
val predictions = response.autocompletePredictions
adapter.setPredictions(predictions)
progressBar.isIndeterminate = false
viewAnimator.displayedChild = if (predictions.isEmpty()) 0 else 1
}.addOnFailureListener { exception: Exception? ->
progressBar.isIndeterminate = false
if (exception is ApiException) {
Log.e(TAG, "Place not found: " + exception.statusCode)
placesClient.findAutocompletePredictions(newRequest)
.addOnSuccessListener { response ->
val predictions = response.autocompletePredictions
adapter.setPredictions(predictions)
progressBar.isIndeterminate = false
viewAnimator.displayedChild = if (predictions.isEmpty()) 0 else 1
}.addOnFailureListener { exception: Exception? ->
progressBar.isIndeterminate = false
if (exception is ApiException) {
Log.e(TAG, "Place not found: " + exception.message)
wangela marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
}


/**
* Performs a Geocoding API request and displays the result in a dialog.
* Be sure to enable Geocoding API in your project and API key restrictions.
*
* @see https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically
*/
Expand All @@ -186,6 +193,11 @@ class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() {
// Use the HTTP request URL for Geocoding API to get geographic coordinates for the place
val request = JsonObjectRequest(Request.Method.GET, requestURL, null, { response ->
try {
val status: String = response.getString("status")
if (status != "OK") {
Log.e(TAG, "$status " + response.getString("error_message"))
}

// Inspect the value of "results" and make sure it's not empty
val results: JSONArray = response.getJSONArray("results")
if (results.length() == 0) {
Expand Down Expand Up @@ -215,9 +227,37 @@ class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() {
.show()
}

/**
* Performs a Place Details request and displays the result in a dialog.
*
* @see https://developers.google.com/maps/documentation/places/android-sdk/place-details#maps_places_get_place_by_id-kotlin
*/
private fun fetchPlaceAndDisplay(placePrediction: AutocompletePrediction) {
// Specify the fields to return.
val placeFields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS)

// Construct a request object, passing the place ID and fields array.
val request = FetchPlaceRequest.newInstance(placePrediction.placeId, placeFields)

placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
AlertDialog.Builder(this)
.setTitle(place.name)
.setMessage("located at:\n" + place.address)
.setPositiveButton(android.R.string.ok, null)
.show()
Log.i(TAG, "Place found: ${place.name}")
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e(TAG, "Place not found: ${exception.message} ${exception.statusCode}")
}
}
}


companion object {
private val TAG = ProgrammaticAutocompleteToolbarActivity::class.java.simpleName
private val TAG = ProgrammaticAutocompleteGeocodingActivity::class.java.simpleName
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".programmatic_autocomplete.ProgrammaticAutocompleteToolbarActivity">
tools:context=".programmatic_autocomplete.ProgrammaticAutocompleteGeocodingActivity">

<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
Expand Down
2 changes: 1 addition & 1 deletion demo-kotlin/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@

<string name="programmatic_autocomplete_geocoding">Programmatic Autocomplete + Geocoding</string>
<string name="search">Search</string>
<string name="search_a_place">Search a Place</string>
<string name="search_a_place">Search for a Place</string>
<string name="programmatic_place_predictions_instructions">This activity demonstrates as-you-type programmatic place predictions. Tap on the search icon on the toolbar and search for a place.</string>

<!-- FIND CURRENT PLACE -->
Expand Down