Search specific nearby places using google places api web services for android

Search specific nearby places using google places api web services for android

Content Index :

Search specific nearby places using google places api web services for android
Tag : android , By : Star Gryphon
Date : December 01 2020, 05:00 PM

will help you First of all, you're connecting to GooglePlayServices, but never actually using GooglePlayServices for the location.
Instead of this:
Location myLocation = locationManager.getLastKnownLocation(provider);
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsActivity2 extends AppCompatActivity
        implements OnMapReadyCallback,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    boolean firstRun = true;

    protected void onCreate(Bundle savedInstanceState)

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    public void onPause() {

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    public void onMapReady(GoogleMap googleMap)

        //Initialize Google Play Services

    public StringBuilder sbMethod(Location currentLocation) {
        //current location
        double mLatitude = currentLocation.getLatitude();
        double mLongitude = currentLocation.getLongitude();

        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        sb.append("location=" + mLatitude + "," + mLongitude);
        sb.append("&types=" + "restaurant");


        Log.d("Map", "<><>api: " + sb.toString());

        return sb;

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)

    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    public void onConnectionSuspended(int i) {}

    public void onConnectionFailed(ConnectionResult connectionResult) {}

    public void onLocationChanged(Location location)
        mLastLocation = location;
        if (mCurrLocationMarker != null) {

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.title("Current Position");
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera

        //query places with current location
        StringBuilder sbValue = new StringBuilder(sbMethod(location));
        PlacesTask placesTask = new PlacesTask();

        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    private class PlacesTask extends AsyncTask<String, Integer, String>

        String data = null;

        // Invoked by execute() method of this object
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            return data;

        // Executed after the complete execution of doInBackground() method
        protected void onPostExecute(String result) {
            Log.d("result", "<><> result: " + result);
            ParserTask parserTask = new ParserTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParserTask

    private String downloadUrl(String strUrl) throws IOException
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {

            data = sb.toString();


        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
        return data;

    private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        protected List<HashMap<String, String>> doInBackground(String... jsonData) {

            List<HashMap<String, String>> places = null;
            Place_JSON placeJson = new Place_JSON();

            try {
                jObject = new JSONObject(jsonData[0]);

                places = placeJson.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            return places;

        // Executed after the complete execution of doInBackground() method
        protected void onPostExecute(List<HashMap<String, String>> list) {

            Log.d("Map", "list size: " + list.size());
            // Clears all the existing markers;
            if (!firstRun) {

            firstRun = false;

            for (int i = 0; i < list.size(); i++) {

                // Creating a marker
                MarkerOptions markerOptions = new MarkerOptions();

                // Getting a place from the places list
                HashMap<String, String> hmPlace = list.get(i);

                // Getting latitude of the place
                double lat = Double.parseDouble(hmPlace.get("lat"));

                // Getting longitude of the place
                double lng = Double.parseDouble(hmPlace.get("lng"));

                // Getting name
                String name = hmPlace.get("place_name");

                Log.d("Map", "place: " + name);

                // Getting vicinity
                String vicinity = hmPlace.get("vicinity");

                LatLng latLng = new LatLng(lat, lng);

                // Setting the position for the marker

                markerOptions.title(name + " : " + vicinity);


                // Placing a marker on the touched position
                Marker m = mGoogleMap.addMarker(markerOptions);

    public class Place_JSON {

         * Receives a JSONObject and returns a list
        public List<HashMap<String, String>> parse(JSONObject jObject) {

            JSONArray jPlaces = null;
            try {
                /** Retrieves all the elements in the 'places' array */
                jPlaces = jObject.getJSONArray("results");
            } catch (JSONException e) {
            /** Invoking getPlaces with the array of json object
             * where each json object represent a place
            return getPlaces(jPlaces);

        private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
            int placesCount = jPlaces.length();
            List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> place = null;

            /** Taking each place, parses and adds to list object */
            for (int i = 0; i < placesCount; i++) {
                try {
                    /** Call getPlace with place JSON object to parse the place */
                    place = getPlace((JSONObject) jPlaces.get(i));
                } catch (JSONException e) {
            return placesList;

         * Parsing the Place JSON object
        private HashMap<String, String> getPlace(JSONObject jPlace)

            HashMap<String, String> place = new HashMap<String, String>();
            String placeName = "-NA-";
            String vicinity = "-NA-";
            String latitude = "";
            String longitude = "";
            String reference = "";

            try {
                // Extracting Place name, if available
                if (!jPlace.isNull("name")) {
                    placeName = jPlace.getString("name");

                // Extracting Place Vicinity, if available
                if (!jPlace.isNull("vicinity")) {
                    vicinity = jPlace.getString("vicinity");

                latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
                longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
                reference = jPlace.getString("reference");

                place.put("place_name", placeName);
                place.put("vicinity", vicinity);
                place.put("lat", latitude);
                place.put("lng", longitude);
                place.put("reference", reference);

            } catch (JSONException e) {
            return place;


No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Tag : android , By : MP.
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further
First go through this tutorial for getting familiar with Android Google Maps and this for API 2.

Google Places API nearby search missing places

Tag : google-maps , By : vbanos
Date : March 29 2020, 07:55 AM
it helps some times Here is some code from an old project of mine reagarding:
What is the best approach to map a geocode -> Nearest full street address (with street number)
    // get nearest coords based on given tracking
tb.prototype.getNearestStreetCoords = function(lat, lng, callback) {

    var parentClass = this;

    var nearestStreet = {
        latitude: lat,
        longitude: lng

    if (parentClass.useNearest != true) callback(nearest); 

    var request = {
        origin: new google.maps.LatLng(lat, lng), 
        destination: new google.maps.LatLng(lat, lng),
        travelMode: google.maps.DirectionsTravelMode.DRIVING

    directionsService = new google.maps.DirectionsService();

    directionsService.route(request, function(response, status) {

        if (status == google.maps.DirectionsStatus.OK) {       
        } else {


    // get nearest formatted address based on lat & lng
tb.prototype.getAddress = function(lat, lng, callback) {

    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({'latLng': new google.maps.LatLng(lat, lng)}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {
        } else {

function distance($lat1, $lon1, $lat2, $lon2, $unit = 'M') {

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);

        if ($unit == 'K') {
            return ($miles * 1.609344);
        } else if ($unit == 'N') {
            return ($miles * 0.8684);
        } else {
            return $miles;

Cannot get exact match for google places api using Google Places Nearby Search API

Tag : php , By : FriendL
Date : March 29 2020, 07:55 AM
To fix the issue you can do Yes you are right, the nearbysearch API respond with the list of places that are close to the place you need to search for.
You just need to get the place_id for the place you are searching for and then use the Places API in order to retrieve the detailed results.

google-maps-services-javascript search nearby places

Tag : node.js , By : Hadley
Date : March 29 2020, 07:55 AM
will help you I just started to experiment with the google APIs and I was trying to retrieve all the places near me, by type. https://github.com/googlemaps/google-maps-services-js It works perfectly, if I specify just one type. Ex type: 'museum'. , In googlemaps documentation it specifies

Android: Finding nearby places with Google Places API

Tag : android , By : vitorcoliveira
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • How to fix "Unable to load class 'dagger.Multibindings'" due to problems with gradle
  • VpnService always-on "not supported by this app"
  • Android Studio - Gradle "Sync now" is not Available
  • How do i get my code to give my current location?
  • Could not initialize class sun.util.calendar.ZoneInfoFile while using Flutter firebase-notifications
  • How to implement circular to check / tick animation in Android?
  • Toolbar shadow not showing
  • Android Sqlite get rows where first character is not an Alphabet
  • why I receive "bad request" in my request by retrofit
  • Intercept NavigationUI.onNavDestinationSelected() to make backstack pop with "inclusive = true"
  • I have a problem with the navigation fragments in my proyect, it sais that I need a defaut nav host atribute but I alrea
  • How can I keep a BottomSheetDialogFragment height to always match_parent?
  • How to reference a timerPicker in android studio using kotlin
  • Firebase Crashlytics - get stacktrace info to display during CrashlyticsListener.crashlyticsDidDetectCrashDuringPrevious
  • Schedule a repeating alarm clock
  • Can't assign values outside onTouchListener
  • Is setContentView() needed to inflate a fragment?
  • Why instead of string method returns Kotlin.Unit?
  • Retrofit slash as Query
  • When does onCreateView() get called in this app?
  • Fragment is reloaded each time after rejecting location permission
  • How to read ViewModel data from sttrings.xml list of items
  • Flutter doctor does not see vs code ,VS code does not detect flutter/bin
  • How to build aar in flutter
  • Is displayMetrix xdpi and ydpi accurate?
  • How to detect doubletap on a View?
  • how to play an encrypted file in Android
  • Android: keytool error on the command line when locating debug.keystore
  • Android paint/canvas issue; drawing smooth curves
  • Problems with starting an activity in onStart
  • Performance of map overlay in conjunction with ItemizedOverlay is very poor
  • How to change android indeterminate ProgressBar color?
  • How do I change the Mobile Country Code (MCC) in the Android Emulator?
  • Stop Progressbar manual scrolling in Android
  • Android: download large file
  • Android : uploaded .apk file to server but cant download that .apk file
  • How do I distribute Android app to beta tester without using Market
  • Android Unable to launch the Inbox from a notification
  • Android: Ringer mode changed to silent doesn't stop the phone vibrating
  • Change the side the text appears on a radio button
  • Check the memory usage anp cpu and power of an application in android
  • What is the String 'volumeName' argument of MediaStore.Audio.Playlists.Members.getContentUri referring to?
  • Playing Multiple sounds at the same time in Android
  • Android: how to change the time in emulator?
  • close the soft key pad when i click on other views in android
  • Setting the position within a spinner
  • How to play ringtone/alarm sound in Android
  • How to adjust text font size to fit textview
  • "Android 2.x" vs "Google APIs" for Android AVD Setup
  • How to center buttons on screen horizontally and vertically plus equidistant apart?
  • Discrete seekbar in Android app?
  • Gradle Build Fails - Illegal exception table range in class file com/google/wireless/android/sdk/stats/GradleBuildMemory
  • register has type Long (High Half) but expected Long (Low Half)
  • Is it good idea to use Dispatcher.Main with delay( )?
  • WebView and Advanced View is Not loading partiucalr URL
  • How to show three dots at the end of text view
  • Is it possible to run macros within Android Studio project?
  • Adding a button with default appearance but changed background color
  • What is best way to show notification at a certain time in Android?
  • Jetifier not working when library uses android component and app uses androidx component
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com