Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Finding nearby places with Google Places API

I am trying to get list of the nearby places using Google Places API. I have enabled requried API from Google Devloper Console and have an valid API key. I am able to get my corrent location. After I got the my current location I am trying to get nearby places list but it returns empty.

I have also tried giving null PlaceFilter but it gives same result.

private class MyGoogleMapOnMyLocationListener implements
            OnMyLocationChangeListener,
            ConnectionCallbacks,
            OnConnectionFailedListener {
        private GoogleApiClient mGoogleApiClient;

        @Override
        public void onMyLocationChange(Location location) {
            if (!hasLastLocation) {
                hasLastLocation = true;
                mLastLocation = location;
                Log.d(LOG_TAG, "Location: " + location.toString());

                if (googleMap != null ) {
                    googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(location.getLatitude(), location.getLongitude()), 16.0f));

                    if (mGoogleApiClient == null) {
                        mGoogleApiClient = new GoogleApiClient
                                .Builder(getActivity())
                                .addApi(Places.GEO_DATA_API)
                                .addApi(Places.PLACE_DETECTION_API)
                                .addConnectionCallbacks(this)
                                .addOnConnectionFailedListener(this)
                                .build();
                        mGoogleApiClient.connect();
                    }
                }
            }
        }

        @Override
        public void onConnected(Bundle bundle) {
            Log.d(LOG_TAG, "Google Api Client connected.");

            if (mGoogleApiClient != null) {
                Log.d(LOG_TAG, "Getting nearby places...");

                PendingResult<PlaceLikelihoodBuffer> result =
                        Places.PlaceDetectionApi.getCurrentPlace(mGoogleApiClient, null);

                result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
                    @Override
                    public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
                        Log.d(LOG_TAG, "Got results: " + likelyPlaces.getCount() + " place found.");

                        for (PlaceLikelihood placeLikelihood : likelyPlaces) {
                            Log.i(LOG_TAG, String.format("Place '%s' has likelihood: %g",
                                    placeLikelihood.getPlace().getName(),
                                    placeLikelihood.getLikelihood()));
                        }

                        likelyPlaces.release();
                    }
                });
            }
        }

        @Override
        public void onConnectionSuspended(int i) {

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

        }
    }

Here is my AndroidManifest.xml

Here is my map Fragment

I have followed indtructions from Google Places API for Android

And I have tried accepted answer of this question: Show Current Location and Nearby Places and Route between two places using Google Maps API in Android


UPDATE

I have enabled other map related APIs from Google Developer Console and it worked.

like image 268
Olcay Ertaş Avatar asked Apr 04 '15 10:04

Olcay Ertaş


People also ask

What can I do with Google Places API?

The Places API lets you search for place information using a variety of categories, including establishments, prominent points of interest, and geographic locations. You can search for places either by proximity or a text string.

How do I get nearby places on Android?

Please follow following steps: Open Android Studio and make a new project with name “Google Maps Search Nearby” and company domain application.example.com (I used my company domain i.e androidtutorialpoint.com. Similarly you can use yours). Click Next and choose android version Lollipop.


1 Answers

you may reffer given code and full Demo

import org.apache.http.client.HttpResponseException;

import android.util.Log;

import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.http.json.JsonHttpParser;
import com.google.api.client.json.jackson.JacksonFactory;

@SuppressWarnings("deprecation")
public class GooglePlaces {

    /** Global instance of the HTTP transport. */
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    // Google API Key
    private static final String API_KEY = "<Your KEY>";

    // Google Places serach url's
    private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
    private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
    private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";

    private double _latitude;
    private double _longitude;
    private double _radius;

    /**
     * Searching places
     * @param latitude - latitude of place
     * @params longitude - longitude of place
     * @param radius - radius of searchable area
     * @param types - type of place to search
     * @return list of places
     * */
    public PlacesList search(double latitude, double longitude, double radius, String types)
            throws Exception {

        this._latitude = latitude;
        this._longitude = longitude;
        this._radius = radius;

        try {

            HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
            HttpRequest request = httpRequestFactory
                    .buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
            request.getUrl().put("key", API_KEY);
            request.getUrl().put("location", _latitude + "," + _longitude);
            request.getUrl().put("radius", _radius); // in meters
            request.getUrl().put("sensor", "false");
            if(types != null)
                request.getUrl().put("types", types);

            PlacesList list = request.execute().parseAs(PlacesList.class);
            // Check log cat for places response status
            Log.d("Places Status", "" + list.status);
            return list;

        } catch (HttpResponseException e) {
            Log.e("Error:", e.getMessage());
            return null;
        }

    }

    /**
     * Searching single place full details
     * @param refrence - reference id of place
     *                 - which you will get in search api request
     * */
    public PlaceDetails getPlaceDetails(String reference) throws Exception {
        try {

            HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
            HttpRequest request = httpRequestFactory
                    .buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
            request.getUrl().put("key", API_KEY);
            request.getUrl().put("reference", reference);
            request.getUrl().put("sensor", "false");

            PlaceDetails place = request.execute().parseAs(PlaceDetails.class);

            return place;

        } catch (HttpResponseException e) {
            Log.e("Error in Perform Details", e.getMessage());
            throw e;
        }
    }

    /**
     * Creating http request Factory
     * */
    public static HttpRequestFactory createRequestFactory(
            final HttpTransport transport) {
        return transport.createRequestFactory(new HttpRequestInitializer() {
            public void initialize(HttpRequest request) {
                GoogleHeaders headers = new GoogleHeaders();
                headers.setApplicationName("AndroidHive-Places-Test");
                request.setHeaders(headers);
                JsonHttpParser parser = new JsonHttpParser(new JacksonFactory());
                request.addParser(parser);
            }
        });
    }

}
like image 188
RBK Avatar answered Sep 27 '22 17:09

RBK