com.google.android.gms.location.places.Places Java Examples

The following examples show how to use com.google.android.gms.location.places.Places. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void guessCurrentPlace() {
    PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace( mGoogleApiClient, null );
    result.setResultCallback( new ResultCallback<PlaceLikelihoodBuffer>() {
        @Override
        public void onResult( PlaceLikelihoodBuffer likelyPlaces ) {

            PlaceLikelihood placeLikelihood = likelyPlaces.get( 0 );
            String content = "";
            if( placeLikelihood != null && placeLikelihood.getPlace() != null && !TextUtils.isEmpty( placeLikelihood.getPlace().getName() ) )
                content = "Most likely place: " + placeLikelihood.getPlace().getName() + "\n";
            if( placeLikelihood != null )
                content += "Percent change of being there: " + (int) ( placeLikelihood.getLikelihood() * 100 ) + "%";
            mTextView.setText( content );

            likelyPlaces.release();
        }
    });
}
 
Example #2
Source File: SearchClinics.java    From Crimson with Apache License 2.0 6 votes vote down vote up
private void getLocation() {

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .enableAutoManage(this, this)
                .build();

        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)
                .setFastestInterval(1 * 1000);

    }
 
Example #3
Source File: MainActivity.java    From AndroidDemoProjects with Apache License 2.0 6 votes vote down vote up
private void findPlaceById( String id ) {
    if( TextUtils.isEmpty( id ) || mGoogleApiClient == null || !mGoogleApiClient.isConnected() )
        return;

   Places.GeoDataApi.getPlaceById( mGoogleApiClient, id ) .setResultCallback( new ResultCallback<PlaceBuffer>() {
       @Override
       public void onResult(PlaceBuffer places) {
           if( places.getStatus().isSuccess() ) {
               Place place = places.get( 0 );
               displayPlace( place );
               mPredictTextView.setText( "" );
               mAdapter.clear();
           }

           //Release the PlaceBuffer to prevent a memory leak
           places.release();
       }
   } );
}
 
Example #4
Source File: SuggestionsProvider.java    From Nibo with MIT License 6 votes vote down vote up
public Observable<Place> getPlaceByID(final String placeId) {
    return new Observable<Place>() {
        @Override
        protected void subscribeActual(final Observer<? super Place> observer) {
            Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId)
                    .setResultCallback(new ResultCallback<PlaceBuffer>() {
                        @Override
                        public void onResult(@NonNull PlaceBuffer places) {
                            if (places.getStatus().isSuccess()) {
                                final Place thatPlace = places.get(0);
                                LatLng queriedLocation = thatPlace.getLatLng();
                                Log.v("Latitude is", "" + queriedLocation.latitude);
                                Log.v("Longitude is", "" + queriedLocation.longitude);

                                observer.onNext(thatPlace.freeze());
                            } else {

                            }
                            places.release();
                        }
                    });
        }
    }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}
 
Example #5
Source File: MainActivity.java    From Nibo with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .enableAutoManage(this, 0, this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();

    initView();

}
 
Example #6
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Act upon new check-outs when they appear.
 */
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
    String placeId = dataSnapshot.getKey();
    if (placeId != null) {
        Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId)
                .setResultCallback(new ResultCallback<PlaceBuffer>() {
                           @Override
                           public void onResult(PlaceBuffer places) {
                               LatLng location = places.get(0).getLatLng();
                               addPointToViewPort(location);
                               mMap.addMarker(new MarkerOptions().position(location));
                               places.release();
                           }
                       }
                );
    }
}
 
Example #7
Source File: MapsActivity.java    From io2015-codelabs with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    // Set up Google Maps
    SupportMapFragment mapFragment = (SupportMapFragment)
            getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Set up the API client for Places API
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Places.GEO_DATA_API)
            .build();
    mGoogleApiClient.connect();

    // Set up Firebase
    Firebase.setAndroidContext(this);
    mFirebase = new Firebase(FIREBASE_URL);
    mFirebase.child(FIREBASE_ROOT_NODE).addChildEventListener(this);
}
 
Example #8
Source File: AutoCompleteAdapter.java    From AutocompleteLocation with Apache License 2.0 6 votes vote down vote up
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
  if (mGoogleApiClient.isConnected()) {
    PendingResult<AutocompletePredictionBuffer> results =
        Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
            mBounds, mPlaceFilter);

    AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);

    final Status status = autocompletePredictions.getStatus();
    if (!status.isSuccess()) {
      Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
          Toast.LENGTH_SHORT).show();
      autocompletePredictions.release();
      return null;
    }

    return DataBufferUtils.freezeAndClose(autocompletePredictions);
  }
  return null;
}
 
Example #9
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 6 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    /*
     Retrieve the place ID of the selected item from the Adapter.
     The adapter stores each Place suggestion in a AutocompletePrediction from which we
     read the place ID and title.
      */
    final AutocompletePrediction item = mAdapter.getItem(position);
    final String placeId = item.getPlaceId();
    final CharSequence primaryText = item.getPrimaryText(null);

    Log.i(TAG, "Autocomplete item selected: " + primaryText);

    /*
     Issue a request to the Places Geo Data API to retrieve a Place object with additional
     details about the place.
      */
    PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
            .getPlaceById(mGoogleApiClient, placeId);
    placeResult.setResultCallback(mUpdatePlaceDetailsCallback);

    Toast.makeText(getApplicationContext(), "Clicked: " + primaryText,
            Toast.LENGTH_SHORT).show();
    Log.i(TAG, "Called getPlaceById to get Place details for " + placeId);
}
 
Example #10
Source File: PlaceSearchDialog.java    From place-search-dialog with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(context)
            //.enableAutoManage(activity, 0 /* clientId */, this)
            .addApi(Places.GEO_DATA_API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
 
Example #11
Source File: AutoCompleteAdapter.java    From AndroidDemoProjects with Apache License 2.0 5 votes vote down vote up
private void displayPredictiveResults( String query )
{
    //Southwest corner to Northeast corner.
    LatLngBounds bounds = new LatLngBounds( new LatLng( 39.906374, -105.122337 ), new LatLng( 39.949552, -105.068779 ) );

    //Filter: https://developers.google.com/places/supported_types#table3
    List<Integer> filterTypes = new ArrayList<Integer>();
    filterTypes.add( Place.TYPE_ESTABLISHMENT );

    Places.GeoDataApi.getAutocompletePredictions( mGoogleApiClient, query, bounds, AutocompleteFilter.create( filterTypes ) )
        .setResultCallback (
            new ResultCallback<AutocompletePredictionBuffer>() {
                @Override
                public void onResult( AutocompletePredictionBuffer buffer ) {

                    if( buffer == null )
                        return;

                    if( buffer.getStatus().isSuccess() ) {
                        for( AutocompletePrediction prediction : buffer ) {
                            //Add as a new item to avoid IllegalArgumentsException when buffer is released
                            add( new AutoCompletePlace( prediction.getPlaceId(), prediction.getDescription() ) );
                        }
                    }

                    //Prevent memory leak by releasing buffer
                    buffer.release();
                }
            }, 60, TimeUnit.SECONDS );
}
 
Example #12
Source File: PlacesAutoCompleteActivity.java    From GoogleAutoCompleteWithRecyclerView with GNU General Public License v2.0 5 votes vote down vote up
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .build();
}
 
Example #13
Source File: MainActivity.java    From android-play-places with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Construct a GeoDataClient for the Google Places API for Android.
    mGeoDataClient = Places.getGeoDataClient(this, null);

    setContentView(R.layout.activity_main);

    // Retrieve the AutoCompleteTextView that will display Place suggestions.
    mAutocompleteView = (AutoCompleteTextView)
            findViewById(R.id.autocomplete_places);

    // Register a listener that receives callbacks when a suggestion has been selected
    mAutocompleteView.setOnItemClickListener(mAutocompleteClickListener);

    // Retrieve the TextViews that will display details and attributions of the selected place.
    mPlaceDetailsText = (TextView) findViewById(R.id.place_details);
    mPlaceDetailsAttribution = (TextView) findViewById(R.id.place_attribution);

    // Set up the adapter that will retrieve suggestions from the Places Geo Data Client.
    mAdapter = new PlaceAutocompleteAdapter(this, mGeoDataClient, BOUNDS_GREATER_SYDNEY, null);
    mAutocompleteView.setAdapter(mAdapter);

    // Set up the 'clear text' button that clears the text in the autocomplete view
    Button clearButton = (Button) findViewById(R.id.button_clear);
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAutocompleteView.setText("");
        }
    });
}
 
Example #14
Source File: PlaceAutocompleteAdapter.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Submits an autocomplete query to the Places Geo Data Autocomplete API.
 * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
 * objects to store the Place ID and description that the API returns.
 * Returns an empty list if no results were found.
 * Returns null if the API client is not available or the query did not complete
 * successfully.
 * This method MUST be called off the main UI thread, as it will block until data is returned
 * from the API, which may include a network request.
 *
 * @param constraint Autocomplete query string
 * @return Results from the autocomplete API or null if the query was not successful.
 * @see Places#GEO_DATA_API#getAutocomplete(CharSequence)
 * @see AutocompletePrediction#freeze()
 */
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            autocompletePredictions.release();
            return null;
        }


        // Freeze the results immutable representation that can be stored safely.
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    return null;
}
 
Example #15
Source File: SearchPlaceOnMapActivity.java    From Airbnb-Android-Google-Map-View with MIT License 5 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
    final String placeId = String.valueOf(item.placeId);


    PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
            .getPlaceById(mGoogleApiClient, placeId);
    placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
 
Example #16
Source File: CustomAutoCompleteAdapter.java    From Place-Search-Service with MIT License 5 votes vote down vote up
public CustomAutoCompleteAdapter(Context context) {
    super(context, android.R.layout.simple_dropdown_item_1line,
            new ArrayList<Place>());
    mContext = context;
    geoDataClient = Places.getGeoDataClient(mContext, null);


}
 
Example #17
Source File: PlaceAutocompleteAdapter.java    From place-search-dialog with Apache License 2.0 5 votes vote down vote up
/**
 * Submits an autocomplete query to the Places Geo Data Autocomplete API.
 * Results are returned as frozen AutocompletePrediction objects, ready to be cached.
 * objects to store the Place ID and description that the API returns.
 * Returns an empty list if no results were found.
 * Returns null if the API client is not available or the query did not complete
 * successfully.
 * This method MUST be called off the main UI thread, as it will block until data is returned
 * from the API, which may include a network request.
 *
 * @param constraint Autocomplete query string
 * @return Results from the autocomplete API or null if the query was not successful.
 * @see Places#GEO_DATA_API#getAutocomplete(CharSequence)
 * @see AutocompletePrediction#freeze()
 */
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG, "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
            autocompletePredictions.release();
            return null;
        }

        Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                + " predictions.");

        // Freeze the results immutable representation that can be stored safely.
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    Log.e(TAG, "Google API client is not connected for autocomplete query.");
    return null;
}
 
Example #18
Source File: PhotoTask.java    From protrip with MIT License 5 votes vote down vote up
/**
 * Loads the first photo for a place id from the Geo Data API.
 * The place id must be the first (and only) parameter.
 */
@Override
protected AttributedPhoto doInBackground(String... params) {
    if (params.length != 1) {
        return null;
    }
    final String placeId = params[0];
    AttributedPhoto attributedPhoto = null;

    PlacePhotoMetadataResult result = Places.GeoDataApi
            .getPlacePhotos(mGoogleApiClient, placeId).await();

    if (result.getStatus().isSuccess()) {
        PlacePhotoMetadataBuffer photoMetadataBuffer = result.getPhotoMetadata();
        if (photoMetadataBuffer.getCount() > 0 && !isCancelled()) {
            // Get the first bitmap and its attributions.
            PlacePhotoMetadata photo = photoMetadataBuffer.get(0);
            CharSequence attribution = photo.getAttributions();
            // Load a scaled bitmap for this photo.
            Bitmap image = photo.getScaledPhoto(mGoogleApiClient, mWidth, mHeight).await()
                    .getBitmap();

            attributedPhoto = new AttributedPhoto(attribution, image);
        }
        // Release the PlacePhotoMetadataBuffer.
        photoMetadataBuffer.release();
    }
    return attributedPhoto;
}
 
Example #19
Source File: AutoCompleteLocation.java    From AutocompleteLocation with Apache License 2.0 5 votes vote down vote up
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  UIUtils.hideKeyboard(AutoCompleteLocation.this.getContext(), AutoCompleteLocation.this);
  final AutocompletePrediction item = mAutoCompleteAdapter.getItem(position);
  if (item != null) {
    final String placeId = item.getPlaceId();
    PendingResult<PlaceBuffer> placeResult =
        Places.GeoDataApi.getPlaceById(mGoogleApiClient, placeId);
    placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
  }
}
 
Example #20
Source File: AutoCompleteLocation.java    From AutocompleteLocation with Apache License 2.0 5 votes vote down vote up
public AutoCompleteLocation(Context context, AttributeSet attrs) {
  super(context, attrs);
  Resources resources = context.getResources();
  TypedArray typedArray =
      context.obtainStyledAttributes(attrs, R.styleable.AutoCompleteLocation, 0, 0);
  Drawable background =
      typedArray.getDrawable(R.styleable.AutoCompleteLocation_background_layout);
  if (background == null) {
    background = resources.getDrawable(R.drawable.bg_rounded_white);
  }
  String hintText = typedArray.getString(R.styleable.AutoCompleteLocation_hint_text);
  if (hintText == null) {
    hintText = resources.getString(R.string.default_hint_text);
  }
  int hintTextColor = typedArray.getColor(R.styleable.AutoCompleteLocation_hint_text_color,
      resources.getColor(R.color.default_hint_text));
  int textColor = typedArray.getColor(R.styleable.AutoCompleteLocation_text_color,
      resources.getColor(R.color.default_text));
  int padding = resources.getDimensionPixelSize(R.dimen.default_padding);
  typedArray.recycle();

  setBackground(background);
  setHint(hintText);
  setHintTextColor(hintTextColor);
  setTextColor(textColor);
  setPadding(padding, padding, padding, padding);
  setMaxLines(resources.getInteger(R.integer.default_max_lines));

  mCloseIcon = context.getResources().getDrawable(R.drawable.ic_close);
  mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(Places.GEO_DATA_API)
      .addApi(AppIndex.API)
      .build();
}
 
Example #21
Source File: GoogleClientModule.java    From Nibo with MIT License 5 votes vote down vote up
public GoogleApiClient getGoogleApiClient() {
    if (googleApiClient == null) {
        googleApiClient = new GoogleApiClient
                .Builder(activity)
                .enableAutoManage(activity, 0, connectionFailedListener)
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(connectionCallbacks)
                .addOnConnectionFailedListener(connectionFailedListener)
                .build();
    }

    return googleApiClient;
}
 
Example #22
Source File: PhotoTask.java    From Place-Search-Service with MIT License 5 votes vote down vote up
@Override
protected List<AttributedPhoto> doInBackground(String... params) {
    if (params.length != 1) {
        return null;
    }
    final String placeId = params[0];
    AttributedPhoto attributedPhoto = null;

    PlacePhotoMetadataResult result = Places.GeoDataApi
            .getPlacePhotos(mGoogleApiClient, placeId).await();
    List<AttributedPhoto> list = new ArrayList<>();
    if (result.getStatus().isSuccess()) {
        PlacePhotoMetadataBuffer photoMetadataBuffer = result.getPhotoMetadata();
        if (photoMetadataBuffer.getCount() > 0 && !isCancelled()) {
            for (int index = 0;index<photoMetadataBuffer.getCount();index++) {
                PlacePhotoMetadata photo = photoMetadataBuffer.get(index);
                CharSequence attribution = photo.getAttributions();
                Bitmap image = photo.getScaledPhoto(mGoogleApiClient, mWidth, mHeight).await()
                        .getBitmap();

                attributedPhoto = new AttributedPhoto(attribution, image);
                list.add(attributedPhoto);
            }
        }
        photoMetadataBuffer.release();
    }
    return list;
}
 
Example #23
Source File: PhotoTask.java    From Place-Search-Service with MIT License 5 votes vote down vote up
public PhotoTask(Context context,int width, int height) {
    mHeight = height;
    mWidth = width;
    mGoogleApiClient = new GoogleApiClient
            .Builder(context)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage((FragmentActivity)context, null)
            .build();
}
 
Example #24
Source File: PlaceAutocompleteAdapter.java    From Airbnb-Android-Google-Map-View with MIT License 4 votes vote down vote up
/**
     * Submits an autocomplete query to the Places Geo Data Autocomplete API.
     * objects to store the Place ID and description that the API returns.
     * Returns an empty list if no results were found.
     * Returns null if the API client is not available or the query did not complete
     * successfully.
     * This method MUST be called off the main UI thread, as it will block until data is returned
     * from the API, which may include a network request.
     *
     * @param constraint Autocomplete query string
     * @return Results from the autocomplete API or null if the query was not successful.
     * @see Places#GEO_DATA_API#getAutocomplete(CharSequence)
     */
    private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) {
        if (mGoogleApiClient.isConnected()) {

            // Submit the query to the autocomplete API and retrieve a PendingResult that will
            // contain the results when the query completes.
            PendingResult<AutocompletePredictionBuffer> results =
                    Places.GeoDataApi
                            .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                    mBounds, mPlaceFilter);

            // This method should have been called off the main UI thread. Block and wait for at most 60s
            // for a result from the API.
            AutocompletePredictionBuffer autocompletePredictions = results
                    .await(60, TimeUnit.SECONDS);

            // Confirm that the query completed successfully, otherwise return null
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                autocompletePredictions.release();
                return null;
            }

            //Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
            //           + " predictions.");
//
            // Copy the results into our own data structure, because we can't hold onto the buffer.
            // AutocompletePrediction objects encapsulate the API response (place ID and description).

            Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                // Get the details of this prediction and copy it into a new PlaceAutocomplete object.
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
                        prediction.getDescription()));
            }

            // Release the buffer now that all data has been copied.
            autocompletePredictions.release();
            return resultList;
        }
        //Log.e(TAG, "Google API client is not connected for autocomplete query.");
        return null;
    }
 
Example #25
Source File: SearchPlaceOnMapActivity.java    From Airbnb-Android-Google-Map-View with MIT License 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_place_on_map);

    getSupportActionBar().setTitle("Search Places");

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    fabAdd= (FloatingActionButton) findViewById(R.id.fab_add);
    fabAdd.setOnClickListener(this);

    mAutocompleteView = (AutoCompleteTextView)
            findViewById(R.id.googleplacesearch);
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, 0 /* clientId */, this)
            .addApi(Places.GEO_DATA_API)
            .build();
    mAdapter = new PlaceAutocompleteAdapter(this, R.layout.google_places_search_items,
            mGoogleApiClient, null, null);

    //TODO:In order to Restrict search to India uncomment this and comment the above line
    /*
    mAdapter = new PlaceAutocompleteAdapter(this, R.layout.google_places_search_items,
            mGoogleApiClient, BOUNDS_GREATER_INDIA, null);
     */
    mAutocompleteView.setAdapter(mAdapter);
    mAutocompleteView.setOnItemClickListener(mAutocompleteClickListener);

    mAutocompleteView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getRawX() >= (mAutocompleteView.getRight() - mAutocompleteView.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {

                    mAutocompleteView.setText("");

                    return true;
                }
            }
            if (event.getRawX() <= (mAutocompleteView.getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) {

                Intent i = new Intent(SearchPlaceOnMapActivity.this, MainActivity.class);
                startActivity(i);

                finish();
                return true;
            }
            return false;
        }
    });
}
 
Example #26
Source File: ViewActivity.java    From memoir with Apache License 2.0 4 votes vote down vote up
public void getCurrentLocation() {
    try {
        // On Marshmallow request for permissions first
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        PERMISSION_ACCESS_FINE_LOCATION);
            } else {
                return;
            }
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
                        PERMISSION_ACCESS_COARSE_LOCATION);
            } else {
                return;
            }
        }

        PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);
        result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
            @Override
            public void onResult(@NonNull PlaceLikelihoodBuffer likelyPlaces) {
                Place place = null;
                float max = 0;
                for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                    float likelihood = placeLikelihood.getLikelihood();
                    if (likelihood > max) {
                        place = placeLikelihood.getPlace();
                        max = placeLikelihood.getLikelihood();
                    }
                }
                if (place == null) {
                    Toast.makeText(getApplicationContext(), R.string.note_location_unable, Toast.LENGTH_SHORT).show();
                } else {
                    note.setLocation(place);
                    refreshLayout();
                }
                likelyPlaces.release();
            }
        });
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(), R.string.note_location_unable, Toast.LENGTH_SHORT).show();
    }
}
 
Example #27
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Construct a GoogleApiClient for the {@link Places#GEO_DATA_API} using AutoManage
    // functionality, which automatically sets up the API client to handle Activity lifecycle
    // events. If your activity does not extend FragmentActivity, make sure to call connect()
    // and disconnect() explicitly.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, 0 /* clientId */, this)
            .addApi(Places.GEO_DATA_API)
            .build();

    setContentView(R.layout.activity_main);

    // Retrieve the AutoCompleteTextView that will display Place suggestions.
    mAutocompleteView = (AutoCompleteTextView)
            findViewById(R.id.autocomplete_places);

    // Register a listener that receives callbacks when a suggestion has been selected
    mAutocompleteView.setOnItemClickListener(mAutocompleteClickListener);

    // Retrieve the TextViews that will display details and attributions of the selected place.
    mPlaceDetailsText = (TextView) findViewById(R.id.place_details);
    mPlaceDetailsAttribution = (TextView) findViewById(R.id.place_attribution);

    // Set up the adapter that will retrieve suggestions from the Places Geo Data API that cover
    // the entire world.
    mAdapter = new PlaceAutocompleteAdapter(this, mGoogleApiClient, BOUNDS_GREATER_SYDNEY,
            null);
    mAutocompleteView.setAdapter(mAdapter);

    // Set up the 'clear text' button that clears the text in the autocomplete view
    Button clearButton = (Button) findViewById(R.id.button_clear);
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAutocompleteView.setText("");
        }
    });
}
 
Example #28
Source File: ViewActivity.java    From memoir with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view);
    ButterKnife.bind(this);

    // Toolbar
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Setup RTEditing
    RTApi rtApi = new RTApi(this, new RTProxyImpl(this), new RTMediaFactoryImpl(this, true));
    rtManager = new RTManager(rtApi, savedInstanceState);
    rtManager.registerEditor(noteBody, true);

    // Setup UI
    int actionType = getIntent().getIntExtra(ACTION_TYPE_KEY, ACTION_TYPE_NEW);
    String noteId;
    if (actionType == ACTION_TYPE_EDIT) {
        noteId = getIntent().getStringExtra(NOTE_ID_KEY);
        note = NotesDatabase.getInstance(this).getNoteByID(noteId);
        refreshLayout();
    } else {
        noteId = UUID.randomUUID().toString();
        note = new Note(noteId, "Untitled", "");
        NotesDatabase.getInstance(this).addNote(note);
        if (getIntent().getExtras().containsKey(NOTE_DATE_KEY)) {
            SimpleDateFormat fmt = new SimpleDateFormat("ddMMyyyy");
            try {
                note.calendar.setTime(fmt.parse(getIntent().getStringExtra(NOTE_DATE_KEY)));
            } catch (Exception ignored) {}
        }
        refreshLayout();
    }

    // Google API Client
    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, null)
            .build();
    mGoogleApiClient.connect();
}
 
Example #29
Source File: PlacesAutoCompleteAdapter.java    From GoogleAutoCompleteWithRecyclerView with GNU General Public License v2.0 4 votes vote down vote up
private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i("", "Starting autocomplete query for: " + constraint);

        // Submit the query to the autocomplete API and retrieve a PendingResult that will
        // contain the results when the query completes.
        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        // This method should have been called off the main UI thread. Block and wait for at most 60s
        // for a result from the API.
        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        // Confirm that the query completed successfully, otherwise return null
        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(mContext, "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            Log.e("", "Error getting autocomplete prediction API call: " + status.toString());
            autocompletePredictions.release();
            return null;
        }

        Log.i("", "Query completed. Received " + autocompletePredictions.getCount()
                + " predictions.");

        // Copy the results into our own data structure, because we can't hold onto the buffer.
        // AutocompletePrediction objects encapsulate the API response (place ID and description).

        Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
        ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount());
        while (iterator.hasNext()) {
            AutocompletePrediction prediction = iterator.next();
            // Get the details of this prediction and copy it into a new PlaceAutocomplete object.
            resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
                    prediction.getDescription()));
        }

        // Release the buffer now that all data has been copied.
        autocompletePredictions.release();

        return resultList;
    }
    Log.e("", "Google API client is not connected for autocomplete query.");
    return null;
}
 
Example #30
Source File: SuggestionsProvider.java    From Nibo with MIT License 4 votes vote down vote up
public Observable<Collection<NiboSearchSuggestionItem>> getSuggestions(final String query) {
    final List<NiboSearchSuggestionItem> placeSuggestionItems = new ArrayList<>();

    if (mGoogleApiClient == null) {
        Log.d(TAG, "Google play services cannot be null");
    }

    return new Observable<Collection<NiboSearchSuggestionItem>>() {
        @Override
        protected void subscribeActual(final Observer<? super Collection<NiboSearchSuggestionItem>> observer) {
            Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient, query, null, null)
                    .setResultCallback(
                            new ResultCallback<AutocompletePredictionBuffer>() {
                                @Override
                                public void onResult(@NonNull AutocompletePredictionBuffer buffer) {
                                    placeSuggestionItems.clear();
                                    if (buffer.getStatus().isSuccess()) {
                                        Log.d(TAG, buffer.toString() + " " + buffer.getCount());

                                        for (AutocompletePrediction prediction : buffer) {
                                            Log.d(TAG, prediction.getFullText(null).toString());
                                            //Add as a new item to avoid IllegalArgumentsException when buffer is released
                                            NiboSearchSuggestionItem placeSuggestion = new NiboSearchSuggestionItem(
                                                    prediction.getFullText(null).toString(),
                                                    prediction.getPlaceId(), NiboSearchSuggestionItem.TYPE_SEARCH_ITEM_SUGGESTION,
                                                    mContext.getResources().getDrawable(R.drawable.ic_map_marker_def)
                                            );

                                            placeSuggestionItems.add(placeSuggestion);
                                        }

                                        observer.onNext(placeSuggestionItems);

                                    } else {
                                        Log.d(TAG, buffer.toString());
                                        observer.onError(new Throwable(buffer.getStatus().getStatusMessage()));
                                    }
                                    //Prevent memory leak by releasing buffer
                                    buffer.release();
                                }
                            }, 60, TimeUnit.SECONDS);

        }
    };
}