Search in sources :

Example 1 with AutocompletePrediction

use of com.google.android.libraries.places.api.model.AutocompletePrediction in project android-places-demos by googlemaps.

the class PlaceAutocompleteActivity method programmaticPlacePredictions.

// [END maps_places_on_activity_result]
private void programmaticPlacePredictions(String query) {
    // [START maps_places_programmatic_place_predictions]
    // Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
    // and once again when the user makes a selection (for example when calling fetchPlace()).
    AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
    // Create a RectangularBounds object.
    RectangularBounds bounds = RectangularBounds.newInstance(new LatLng(-33.880490, 151.184363), new LatLng(-33.858754, 151.229596));
    // Use the builder to create a FindAutocompletePredictionsRequest.
    FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder().setLocationBias(bounds).setOrigin(new LatLng(-33.8749937, 151.2041382)).setCountries("AU", "NZ").setTypeFilter(TypeFilter.ADDRESS).setSessionToken(token).setQuery(query).build();
    placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
        for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
            Log.i(TAG, prediction.getPlaceId());
            Log.i(TAG, prediction.getPrimaryText(null).toString());
        }
    }).addOnFailureListener((exception) -> {
        if (exception instanceof ApiException) {
            ApiException apiException = (ApiException) exception;
            Log.e(TAG, "Place not found: " + apiException.getStatusCode());
        }
    });
// [END maps_places_programmatic_place_predictions]
}
Also used : TypeFilter(com.google.android.libraries.places.api.model.TypeFilter) AutocompleteSessionToken(com.google.android.libraries.places.api.model.AutocompleteSessionToken) AutocompleteActivity(com.google.android.libraries.places.widget.AutocompleteActivity) Arrays(java.util.Arrays) Bundle(android.os.Bundle) PlacesClient(com.google.android.libraries.places.api.net.PlacesClient) Intent(android.content.Intent) PlaceSelectionListener(com.google.android.libraries.places.widget.listener.PlaceSelectionListener) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) ArrayList(java.util.ArrayList) Log(android.util.Log) LatLng(com.google.android.gms.maps.model.LatLng) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) Places(com.google.android.libraries.places.api.Places) AutocompleteSupportFragment(com.google.android.libraries.places.widget.AutocompleteSupportFragment) Place(com.google.android.libraries.places.api.model.Place) RectangularBounds(com.google.android.libraries.places.api.model.RectangularBounds) List(java.util.List) Nullable(androidx.annotation.Nullable) Autocomplete(com.google.android.libraries.places.widget.Autocomplete) AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction) Status(com.google.android.gms.common.api.Status) NotNull(org.jetbrains.annotations.NotNull) ApiException(com.google.android.gms.common.api.ApiException) AutocompleteActivityMode(com.google.android.libraries.places.widget.model.AutocompleteActivityMode) AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) AutocompleteSessionToken(com.google.android.libraries.places.api.model.AutocompleteSessionToken) RectangularBounds(com.google.android.libraries.places.api.model.RectangularBounds) LatLng(com.google.android.gms.maps.model.LatLng) ApiException(com.google.android.gms.common.api.ApiException)

Example 2 with AutocompletePrediction

use of com.google.android.libraries.places.api.model.AutocompletePrediction in project android-places-demos by googlemaps.

the class PlacePredictionAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(@NonNull PlacePredictionViewHolder holder, int position) {
    final AutocompletePrediction prediction = predictions.get(position);
    holder.setPrediction(prediction);
    holder.itemView.setOnClickListener(v -> {
        if (onPlaceClickListener != null) {
            onPlaceClickListener.onPlaceClicked(prediction);
        }
    });
}
Also used : AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction)

Example 3 with AutocompletePrediction

use of com.google.android.libraries.places.api.model.AutocompletePrediction in project iNaturalistAndroid by inaturalist.

the class LocationChooserActivity method getPlaceDetails.

private void getPlaceDetails(AutocompletePrediction prediction, int index, CountDownLatch latch) {
    new Thread(() -> {
        if (prediction.getPlaceId() == null) {
            // We only show predictions with place IDs (so we can retrieve exact lat/lng)
            latch.countDown();
            return;
        }
        List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG, Place.Field.VIEWPORT);
        FetchPlaceRequest request = FetchPlaceRequest.builder(prediction.getPlaceId(), fields).build();
        mPlacesClient.fetchPlace(request).addOnSuccessListener(fetchPlaceResponse -> {
            // Only when successfully fetching the place details -> add it to the results list
            Place googlePlace = fetchPlaceResponse.getPlace();
            LatLngBounds viewport = googlePlace.getViewport();
            Double radius = null;
            Double latitude = googlePlace.getLatLng().latitude;
            Double longitude = googlePlace.getLatLng().longitude;
            if (viewport != null) {
                LatLng center = viewport.getCenter();
                LatLng northeast = viewport.northeast;
                // Radius is the largest distance from geom center to one of the bounds corners
                radius = Math.max(distanceInMeters(latitude, longitude, center.latitude, center.longitude), distanceInMeters(latitude, longitude, northeast.latitude, northeast.longitude));
            } else {
                radius = 10.0;
            }
            if (index < mPlaces.size()) {
                mPlaces.get(index).accuracy = radius;
                mPlaces.get(index).latitude = latitude;
                mPlaces.get(index).longitude = longitude;
            }
            latch.countDown();
        }).addOnFailureListener(e -> {
            latch.countDown();
        });
    }).start();
}
Also used : Address(android.location.Address) TypeFilter(com.google.android.libraries.places.api.model.TypeFilter) CameraUpdateFactory(com.google.android.gms.maps.CameraUpdateFactory) AutocompleteSessionToken(com.google.android.libraries.places.api.model.AutocompleteSessionToken) Arrays(java.util.Arrays) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ProgressBar(android.widget.ProgressBar) Uri(android.net.Uri) WindowManager(android.view.WindowManager) ImageView(android.widget.ImageView) LocationListener(android.location.LocationListener) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) VisibleRegion(com.google.android.gms.maps.model.VisibleRegion) ActionBar(androidx.appcompat.app.ActionBar) Manifest(android.Manifest) Locale(java.util.Locale) Handler(android.os.Handler) View(android.view.View) Animation(android.view.animation.Animation) ContextCompat(androidx.core.content.ContextCompat) Log(android.util.Log) ConnectivityManager(android.net.ConnectivityManager) LatLng(com.google.android.gms.maps.model.LatLng) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) IntentFilter(android.content.IntentFilter) NetworkInfo(android.net.NetworkInfo) Place(com.google.android.libraries.places.api.model.Place) BroadcastReceiver(android.content.BroadcastReceiver) Geocoder(android.location.Geocoder) Logger(org.tinylog.Logger) DisplayMetrics(android.util.DisplayMetrics) ViewGroup(android.view.ViewGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) TextView(android.widget.TextView) ListView(android.widget.ListView) Location(android.location.Location) Marker(com.google.android.gms.maps.model.Marker) LocationManager(android.location.LocationManager) TextWatcher(android.text.TextWatcher) Context(android.content.Context) KeyEvent(android.view.KeyEvent) PlacesClient(com.google.android.libraries.places.api.net.PlacesClient) LatLngBounds(com.google.android.gms.maps.model.LatLngBounds) Bridge(com.livefront.bridge.Bridge) HashMap(java.util.HashMap) Intent(android.content.Intent) FetchPlaceRequest(com.google.android.libraries.places.api.net.FetchPlaceRequest) Editable(android.text.Editable) ArrayList(java.util.ArrayList) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) PermissionChecker(androidx.core.content.PermissionChecker) AnimationUtils(android.view.animation.AnimationUtils) SuppressLint(android.annotation.SuppressLint) MenuInflater(android.view.MenuInflater) MotionEvent(android.view.MotionEvent) Toast(android.widget.Toast) Menu(android.view.Menu) State(com.evernote.android.state.State) SupportMapFragment(com.google.android.gms.maps.SupportMapFragment) DialogInterface(android.content.DialogInterface) MarkerOptions(com.google.android.gms.maps.model.MarkerOptions) Places(com.google.android.libraries.places.api.Places) IOException(java.io.IOException) Point(android.graphics.Point) RectangularBounds(com.google.android.libraries.places.api.model.RectangularBounds) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) Color(android.graphics.Color) OnMapReadyCallback(com.google.android.gms.maps.OnMapReadyCallback) Configuration(android.content.res.Configuration) AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction) GoogleMap(com.google.android.gms.maps.GoogleMap) EditText(android.widget.EditText) OnClickListener(android.view.View.OnClickListener) FetchPlaceRequest(com.google.android.libraries.places.api.net.FetchPlaceRequest) LatLngBounds(com.google.android.gms.maps.model.LatLngBounds) List(java.util.List) ArrayList(java.util.ArrayList) LatLng(com.google.android.gms.maps.model.LatLng) Place(com.google.android.libraries.places.api.model.Place)

Example 4 with AutocompletePrediction

use of com.google.android.libraries.places.api.model.AutocompletePrediction in project iNaturalistAndroid by inaturalist.

the class LocationChooserActivity method loadPlaceResults.

private void loadPlaceResults(List<AutocompletePrediction> predictions) {
    mWaitForAllResults = new CountDownLatch(predictions.size());
    mPlaces = new ArrayList<>();
    for (AutocompletePrediction prediction : predictions) {
        INatPlace inatPlace = new INatPlace();
        inatPlace.id = prediction.getPlaceId();
        inatPlace.title = prediction.getPrimaryText(null).toString();
        inatPlace.subtitle = prediction.getSecondaryText(null).toString();
        mPlaces.add(inatPlace);
        getPlaceDetails(prediction, mPlaces.size() - 1, mWaitForAllResults);
    }
    // Refresh results
    mPlaceAdapter = new LocationChooserPlaceAdapter(this, mPlaces);
    runOnUiThread(() -> {
        mLocationList.setAdapter(mPlaceAdapter);
        mLoadingSearch.setVisibility(View.GONE);
        mLocationList.setVisibility(View.VISIBLE);
    });
}
Also used : AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 5 with AutocompletePrediction

use of com.google.android.libraries.places.api.model.AutocompletePrediction in project android-places-demos by googlemaps.

the class ProgrammaticAutocompleteToolbarActivity method getPlacePredictions.

/**
 * This method demonstrates the programmatic approach to getting place predictions. The
 * parameters in this request are currently biased to Kolkata, India.
 *
 * @param query the plus code query string (e.g. "GCG2+3M K")
 */
private void getPlacePredictions(String query) {
    // The value of 'bias' biases prediction results to the rectangular region provided
    // (currently Kolkata). Modify these values to get results for another area. Make sure to
    // pass in the appropriate value/s for .setCountries() in the
    // FindAutocompletePredictionsRequest.Builder object as well.
    final LocationBias bias = RectangularBounds.newInstance(// SW lat, lng
    new LatLng(22.458744, 88.208162), // NE lat, lng
    new LatLng(22.730671, 88.524896));
    // Create a new programmatic Place Autocomplete request in Places SDK for Android
    final FindAutocompletePredictionsRequest newRequest = FindAutocompletePredictionsRequest.builder().setSessionToken(sessionToken).setLocationBias(bias).setTypeFilter(TypeFilter.ESTABLISHMENT).setQuery(query).setCountries("IN").build();
    // Perform autocomplete predictions request
    placesClient.findAutocompletePredictions(newRequest).addOnSuccessListener((response) -> {
        List<AutocompletePrediction> predictions = response.getAutocompletePredictions();
        adapter.setPredictions(predictions);
        progressBar.setIndeterminate(false);
        viewAnimator.setDisplayedChild(predictions.isEmpty() ? 0 : 1);
    }).addOnFailureListener((exception) -> {
        progressBar.setIndeterminate(false);
        if (exception instanceof ApiException) {
            ApiException apiException = (ApiException) exception;
            Log.e(TAG, "Place not found: " + apiException.getStatusCode());
        }
    });
}
Also used : DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) TypeFilter(com.google.android.libraries.places.api.model.TypeFilter) AutocompleteSessionToken(com.google.android.libraries.places.api.model.AutocompleteSessionToken) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) ProgressBar(android.widget.ProgressBar) NonNull(androidx.annotation.NonNull) Volley(com.android.volley.toolbox.Volley) PlacesClient(com.google.android.libraries.places.api.net.PlacesClient) GeocodingResult(com.example.placesdemo.model.GeocodingResult) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) GsonBuilder(com.google.gson.GsonBuilder) MenuItem(android.view.MenuItem) JSONException(org.json.JSONException) R(com.example.placesdemo.R) Gson(com.google.gson.Gson) Handler(android.os.Handler) Menu(android.view.Menu) RecyclerView(androidx.recyclerview.widget.RecyclerView) Log(android.util.Log) LocationBias(com.google.android.libraries.places.api.model.LocationBias) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Method(com.android.volley.Request.Method) SearchView(android.widget.SearchView) RequestQueue(com.android.volley.RequestQueue) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) MainActivity(com.example.placesdemo.MainActivity) LatLng(com.google.android.libraries.maps.model.LatLng) Places(com.google.android.libraries.places.api.Places) RectangularBounds(com.google.android.libraries.places.api.model.RectangularBounds) List(java.util.List) Nullable(androidx.annotation.Nullable) BuildConfig(com.example.placesdemo.BuildConfig) ViewAnimator(android.widget.ViewAnimator) AutocompletePrediction(com.google.android.libraries.places.api.model.AutocompletePrediction) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) OnQueryTextListener(android.widget.SearchView.OnQueryTextListener) ApiException(com.google.android.gms.common.api.ApiException) JSONArray(org.json.JSONArray) LocationBias(com.google.android.libraries.places.api.model.LocationBias) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) List(java.util.List) LatLng(com.google.android.libraries.maps.model.LatLng) ApiException(com.google.android.gms.common.api.ApiException)

Aggregations

AutocompletePrediction (com.google.android.libraries.places.api.model.AutocompletePrediction)7 FindAutocompletePredictionsRequest (com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest)4 Bundle (android.os.Bundle)3 Log (android.util.Log)3 AppCompatActivity (androidx.appcompat.app.AppCompatActivity)3 LatLng (com.google.android.gms.maps.model.LatLng)3 Places (com.google.android.libraries.places.api.Places)3 AutocompleteSessionToken (com.google.android.libraries.places.api.model.AutocompleteSessionToken)3 Place (com.google.android.libraries.places.api.model.Place)3 RectangularBounds (com.google.android.libraries.places.api.model.RectangularBounds)3 TypeFilter (com.google.android.libraries.places.api.model.TypeFilter)3 Intent (android.content.Intent)2 Handler (android.os.Handler)2 Menu (android.view.Menu)2 PlacesClient (com.google.android.libraries.places.api.net.PlacesClient)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Manifest (android.Manifest)1 SuppressLint (android.annotation.SuppressLint)1