Search in sources :

Example 1 with FindAutocompletePredictionsRequest

use of com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest 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 FindAutocompletePredictionsRequest

use of com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest in project hypertrack-live-android by hypertrack.

the class SearchPlacePresenter method search.

public void search(String query) {
    if (!state.mapDestinationMode) {
        if (TextUtils.isEmpty(query)) {
            view.updateList(state.getRecentPlaces());
        } else {
            // 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 selectPlace()).
            token = AutocompleteSessionToken.newInstance();
            // Use the builder to create a FindAutocompletePredictionsRequest.
            FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder().setTypeFilter(TypeFilter.GEOCODE).setSessionToken(token).setQuery(query).build();
            placesClient.findAutocompletePredictions(request).addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {

                @Override
                public void onSuccess(FindAutocompletePredictionsResponse response) {
                    view.updateList(PlaceModel.from(response.getAutocompletePredictions()));
                }
            }).addOnFailureListener(new OnFailureListener() {

                @Override
                public void onFailure(@NonNull Exception e) {
                    if (e instanceof ApiException) {
                        ApiException apiException = (ApiException) e;
                        Log.e(TAG, "Place not found: " + apiException.getStatusCode());
                    }
                }
            });
        }
    }
}
Also used : FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) FindAutocompletePredictionsResponse(com.google.android.libraries.places.api.net.FindAutocompletePredictionsResponse) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) ApiException(com.google.android.gms.common.api.ApiException) ApiException(com.google.android.gms.common.api.ApiException)

Example 3 with FindAutocompletePredictionsRequest

use of com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest in project iNaturalistAndroid by inaturalist.

the class LocationChooserActivity method refreshPlaceQuery.

private void refreshPlaceQuery() {
    mHandler.removeCallbacksAndMessages(null);
    mHandler.postDelayed(() -> {
        if (mMap == null)
            return;
        String query = mLocationSearch.getText().toString();
        if (query.length() == 0) {
            mLoadingSearch.setVisibility(View.GONE);
            mLocationList.setVisibility(View.VISIBLE);
            return;
        }
        mLoadingSearch.setVisibility(View.VISIBLE);
        mLocationList.setVisibility(View.GONE);
        VisibleRegion region = mMap.getProjection().getVisibleRegion();
        RectangularBounds bounds;
        if (region.farRight.latitude >= region.nearLeft.latitude) {
            bounds = RectangularBounds.newInstance(region.nearLeft, region.farRight);
        } else {
            bounds = RectangularBounds.newInstance(region.farRight, region.nearLeft);
        }
        if (query.matches(REGEX_LAT_LNG)) {
            // Lat/lng search (not a place search)
            double lat = Double.valueOf(query.split(",")[0].trim());
            double lng = Double.valueOf(query.split(",")[1].trim());
            Logger.tag(TAG).info("Location search for lat/lng: " + lat + "/" + lng);
            mWaitForAllResults = new CountDownLatch(1);
            mPlaces = new ArrayList<>();
            INatPlace inatPlace = new INatPlace();
            inatPlace.id = null;
            inatPlace.title = String.format(getString(R.string.location_lat_lng), lat, lng);
            inatPlace.subtitle = null;
            inatPlace.latitude = lat;
            inatPlace.longitude = lng;
            inatPlace.accuracy = Double.valueOf(0);
            mPlaces.add(inatPlace);
            // Refresh results
            mPlaceAdapter = new LocationChooserPlaceAdapter(this, mPlaces);
            runOnUiThread(() -> {
                mLocationList.setAdapter(mPlaceAdapter);
                mLoadingSearch.setVisibility(View.GONE);
                mLocationList.setVisibility(View.VISIBLE);
            });
            mWaitForAllResults.countDown();
            return;
        }
        FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder().setSessionToken(mAutoCompleteToken).setLocationBias(bounds).setQuery(query).build();
        mQuery = query;
        mPlacesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
            if (!query.equals(mQuery))
                return;
            new Thread(() -> loadPlaceResults(response.getAutocompletePredictions())).start();
        }).addOnFailureListener((exception) -> {
            Logger.tag(TAG).error("Place not found: " + exception);
        });
    }, 500);
}
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) VisibleRegion(com.google.android.gms.maps.model.VisibleRegion) FindAutocompletePredictionsRequest(com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest) RectangularBounds(com.google.android.libraries.places.api.model.RectangularBounds) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with FindAutocompletePredictionsRequest

use of com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest 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

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 ApiException (com.google.android.gms.common.api.ApiException)3 Places (com.google.android.libraries.places.api.Places)3 AutocompletePrediction (com.google.android.libraries.places.api.model.AutocompletePrediction)3 AutocompleteSessionToken (com.google.android.libraries.places.api.model.AutocompleteSessionToken)3 RectangularBounds (com.google.android.libraries.places.api.model.RectangularBounds)3 TypeFilter (com.google.android.libraries.places.api.model.TypeFilter)3 PlacesClient (com.google.android.libraries.places.api.net.PlacesClient)3 List (java.util.List)3 Intent (android.content.Intent)2 Handler (android.os.Handler)2 Menu (android.view.Menu)2 MenuItem (android.view.MenuItem)2 ProgressBar (android.widget.ProgressBar)2 Manifest (android.Manifest)1 SuppressLint (android.annotation.SuppressLint)1 BroadcastReceiver (android.content.BroadcastReceiver)1