Main navigation

Google Maps Search Nearby : Displaying Nearby Places using Google Places API and Google Maps API V2

adsense

Pre-requisites:

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
2) A real time android device (Smartphone or Tablet) configured with Android Studio. .
3) A basic knowledge of Android lifecycle and different classes & functions used in Android Studio.

Before going through this post we will suggest you to first have a look at our post on How to get current location in Android Google Map. That information (inside link) will be used in this post.

Now let’s make it. We hope you would have already made an App to display current user location. So we are not repeating that part now.

Creating new project

Please follow following steps:

  1. 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).
  2. Click Next and choose android version Lollipop. Again Click Next and Choose Google Maps Activity (as shown in following pic).
  3. Google_Map_Activity

  4. Leave all things remaining same and Click Finish.

Now you will be able to see three files:

  1. google_maps_api.xml (…/GoogleMapsSearchNearby/app/src/debug/res/values/google_maps_api.xml)
  2. MapsActivity.java (…/GoogleMapsSearchNearby/app/src/main/java/com/androidtutorialpoint/googlemapssearchnearby
    /MapsActivity.java)
  3. AndroidManifest.xml ( …/GoogleMapsSearchNearby/app/src/main/AndroidManifest.xml)

Open google_maps_api.xml. Here you will find a lot of information along with a link. Copy-Paste this link in your web browser. Make a Gmail account through which you will configure google play services.

Google Maps Search Nearby

Now at the browser choose “Create New Project” and Click Continue. Following screen will be displayed:

Google Maps Search Nearby

Click on Go to credentials. Below screen will appear.

Google Maps Search Nearby

Create your key by clicking Create. Now a key will be created but there is one big change here as compared to our previous Google Maps tutorials. Here you will need a Server Key. So to generate a Server Key click on Create Credentials and then API Key as shown in the following image:

Google Maps Search Nearby

Click on Server Key. Below screen will appear:

Google Maps Search Nearby

Click Create and copy the Server Key generated. You shall copy and paste this key in google_maps_api.xml. Copy paste it in place where YOUR_KEY_HERE is written:

Code inside google_maps_api.xml is complete.

google_maps_api.xml

<resources>
    <!--
    TODO: Before you run your application, you need a Google Maps API key.

    To get one, follow this link, follow the directions and press "Create" at the end:

    https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx%com.androidtutorialpoint.googlemapsapp

    You can also add your credentials to an existing key, using this line:
    xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx;com.androidtutorialpoint.googlemapsapp

    Alternatively, follow the directions here:
    https://developers.google.com/maps/documentation/android/start#get-key

    Once you have your key (it starts with "AIza"), replace the "google_maps_key"
    string in this file.
    -->
    <string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">LVwrKoLOEMgwUBXGiut0bkFhoAjOiaVemoMlymg</string>     
</resources>

Code Inside AndroidManifest.xml:

If you go inside AndroidManifest.xml then this key will be displayed in meta tags. Here you need to add permissions for accessing location of device. The required permission should be as follows:

ACCESS_NETWORK_STATE – To check network state i.e if we are connected to any network or not.
INTERNET – If we are connected to Internet or not.
ACCESS_COARSE_LOCATION – To determine user’s location using WiFi and mobile. It will give us an approximate location.
ACCESS_FINE_LOCATION – To determine user’s location using GPS. It will give us precise location.
OpenGL ES V2 – Required for Google Maps V2

AndroidManifest.xml

  
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.googlemapsdrawroute"
          xmlns:android="https://schemas.android.com/apk/res/android">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="com.androidtutorialpoint.mymapsappsdirection.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key"/>

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>


Code inside activity_maps.xml:

Here we will add three buttons each for Restaurant, Hospitals and Schools such that when user clicks on Restaurant then markers will be added on nearby restaurants. Similarly in case of other two buttons. For this, we will use FrameLayout . Refer below code:

activity_maps.xml

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">

<fragment android:id="@+id/map"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          xmlns:android="https://schemas.android.com/apk/res/android"
          xmlns:map="https://schemas.android.com/apk/res-auto"
          xmlns:tools="https://schemas.android.com/tools"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="com.androidtutorialpoint.googlemapsnearbyplaces.MapsActivity"/>

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
                  xmlns:tools="https://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">

        <Button
            android:id="@+id/btnRestaurant"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nearby Restaurants" />

        <Button
            android:id="@+id/btnHospital"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nearby Hospitals" />

        <Button
            android:id="@+id/btnSchool"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nearby Schools" />

    </LinearLayout>
</FrameLayout>

Note: Please see your build.gradle file. It should have following code:

dependencies {

compile fileTree(dir: ‘libs’, include: [‘*.jar’])

compile ‘com.android.support:appcompat-v7:21.0.3’

compile 'com.google.android.gms:play-services:8.4.0'

}

Third line compile ‘com.google.android.gms:play-services:8.4.0’ is responsible for inserting Google Play Services. Please make sure this line is present in build.gradle

MapsActivity.java Code of Google Maps Search Nearby App

This is the main part of our code. We will divide it into parts to get a grasp on it. Here we won’t discuss code related to getting current user location. You can get that information here.

We will divide our project i.e. Google Maps Search Nearby into different classes so that user can easily debug code. Here we will make three classes apart from MainActivity.java i.e. GetNearbyPlacesData.java, DataParser.java and DownloadUrl.java.

First of all, we will check if Google Play Services available or not in onCreate() function of MainActivity.java. For that we will use function CheckGooglePlayServices().

CheckGooglePlayServices()

private boolean CheckGooglePlayServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int result = googleAPI.isGooglePlayServicesAvailable(this);
        if(result != ConnectionResult.SUCCESS) {
            if(googleAPI.isUserResolvableError(result)) {
                googleAPI.getErrorDialog(this, result,
                        0).show();
            }
            return false;
        }
        return true;
    }

GoogleApiAvailability is the Helper class for verifying that the Google Play services APK is available and up-to-date on android device. If result is ConnectionResult.SUCCESS then connection was successful otherwise, we will return false.

Now comes the heart of our Google Maps Search Nearby code i.e. onMapReady() function. Here we will first build a Google API Client and then enable current user location using mMap.setMyLocationEnabled(true).

buildGoogleApiClient

protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

These steps we have already discussed in our previous tutorial of How to get current location in Android Google Map. So now we will directly refer to the working of buttons and how to get nearby places using it. I will explain here functionality of Nearby Restaurants button. Rest of the two buttons will share same functionality except string passed will be Hospital or School according to button clicked.

Finding nearby Restaurants on Google Maps

We will start its implementation by setting setOnClickListener() and as soon as user clicks on it, code inside onClick(View v) executed.

Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
        btnRestaurant.setOnClickListener(new View.OnClickListener() {
            String Restaurant = "restaurant";
            @Override
            public void onClick(View v) {
                Log.d("onClick", "Button is Clicked");
                mMap.clear();
                String url = getUrl(latitude, longitude, Restaurant);
                Object[] DataTransfer = new Object[2];
                DataTransfer[0] = mMap;
                DataTransfer[1] = url;
                Log.d("onClick", url);
                GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
                getNearbyPlacesData.execute(DataTransfer);
                Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
            }
        });

In the above code first of all Google Map is cleared using mMap.clear() so that any pre-deposited markers are deleted. Then we are making a URL using getUrl() function. It will be used to get information about nearby restaurant on google maps. This URL is made according to Google Developer Guide for nearby places (https://developers.google.com/places/web-service/search). Finally markers are added on nearby restaurants using getNearbyPlacesData.execute(DataTransfer). Let’s see what is this getNearbyPlacesData is in Google Maps Search Nearby App.

GetNearbyPlacesData

Make a new class named GetNearbyPlacesData.java (at path …/GoogleMapsNearbyPlaces/app/src/main/java/com/androidtutorialpoint/
googlemapsnearbyplaces/GetNearbyPlacesData.java). This class should be extended from AsyncTask.

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

    String googlePlacesData;
    GoogleMap mMap;
    String url;

    @Override
    protected String doInBackground(Object... params) {
        try {
            Log.d("GetNearbyPlacesData", "doInBackground entered");
            mMap = (GoogleMap) params[0];
            url = (String) params[1];
            DownloadUrl downloadUrl = new DownloadUrl();
            googlePlacesData = downloadUrl.readUrl(url);
            Log.d("GooglePlacesReadTask", "doInBackground Exit");
        } catch (Exception e) {
            Log.d("GooglePlacesReadTask", e.toString());
        }
        return googlePlacesData;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("GooglePlacesReadTask", "onPostExecute Entered");
        List<HashMap<String, String>> nearbyPlacesList = null;
        DataParser dataParser = new DataParser();
        nearbyPlacesList =  dataParser.parse(result);
        ShowNearbyPlaces(nearbyPlacesList);
        Log.d("GooglePlacesReadTask", "onPostExecute Exit");
    }

    private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
        for (int i = 0; i < nearbyPlacesList.size(); i++) {
            Log.d("onPostExecute","Entered into showing locations");
            MarkerOptions markerOptions = new MarkerOptions();
            HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
            double lat = Double.parseDouble(googlePlace.get("lat"));
            double lng = Double.parseDouble(googlePlace.get("lng"));
            String placeName = googlePlace.get("place_name");
            String vicinity = googlePlace.get("vicinity");
            LatLng latLng = new LatLng(lat, lng);
            markerOptions.position(latLng);
            markerOptions.title(placeName + " : " + vicinity);
            mMap.addMarker(markerOptions);
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        }
    }
}

In the above code DownloadUrl is a class which is used to retrieve data from URL using HttpURLConnection and File handling methods. We will discuss its code after this class. After retrieving data in the form of googlePlacesData we are passing it to onPostExecute method. Data from URL will be in the form JSON which needs to be parsed, So we have made a class named DataParser. DataParser.java file should be added at the same path as MainActivity.java. Code is given at bottom of this tutorial. dataParser.parse(result) is used to parse data and resultant is stored as a list in nearbyPlacesList. Now nearbyPlacesList will have all information about nearby restaurants which we can easily access and add markers on corresponding places. Markers are added in Google Maps using function ShowNearbyPlaces. This is pretty much self explanatory.

DownloadUrl

This class should be made at the same path as MainActivity.java with the name DownloadUrl.java and add following code in it.

public class DownloadUrl {

    public String readUrl(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
            urlConnection.connect();

            // 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) {
                sb.append(line);
            }

            data = sb.toString();
            Log.d("downloadUrl", data.toString());
            br.close();

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

Data returned from web will be in json format which user can get using HttpURLConnection. You can get more information about how to get data over web here. So this task will return JSON data returned from web.

Our code of Google Maps Search Nearby App is complete for Adding markers at nearby restaurants on Google Maps. Now similarly you can do for School and Hospitals. The only change will be in getUrl() function where string will be passed as Hospital or School according to the button clicked.

You can see full code in following files:

MapsActivity.java
GetNearbyPlacesData.java
DataParser.java
DownloadUrl.java

So finally our Google Maps Search Nearby App is complete. We would suggest you to turn on GPS and Internet Connection. Run this Google Maps Search Nearby Places App on any android device. It will first display your location. Now according to button clicked it will display nearby Restaurants, Schools or Hospitals as shown in following figure:

Google Maps Search Nearby



What’s Next

You can now learn how to draw a route on Google Maps between any two location. You can also see how to make this same tutorial using retrofit in our tutorial of Google Maps Nearby Places API using Retrofit Android. We have made a distance calculator app too, have a look at it here: Google Maps Distance Calculator using Google Directions in Google Maps Android API.

Thanks for reading Guys. If you have any doubt or suggestions then please comment. Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter. Happy Coding 🙂

You can download full code below


Android Tutorial Point Download Now


Reader Interactions

Comments

    • Hi Rayaane,

      It could be possible that either your places of interest are not updated in Google Maps or You are providing a very short distance in URL under which there is no restaurant or Hospital. I would suggest you to just copy paste your URL on browser. You will be directly able to see response.

      Thanks for reading. Keep learning 🙂

  1. Very Nice Tutorial Sir, but if i want to add another another activity in which user show the nearby places in list View so how can i do it
    here is my Listview class code:

    public class listviewActivity extends AppCompatActivity {
    ListView lv;

    // KEY Strings
    public static String KEY_REFERENCE = “reference”; // id of the place
    public static String KEY_NAME = “name”; // name of the place
    public static String KEY_VICINITY = “vicinity”; // Place area name

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listview);
    Intent intent = getIntent();
    // Getting listview
    lv = (ListView) findViewById(R.id.list);
    GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
    // getNearbyPlacesData.execute(DataTransfer);
    List list = new ArrayList();
    list.add(“foo”);

    ArrayAdapter arrayAdapter = new ArrayAdapter(
    this,
    android.R.layout.simple_list_item_1,
    list );

    lv.setAdapter(arrayAdapter);
    }
    }

    • Hi Dhruv,

      Can You please specify the portions in which you have doubts. We have tried to describe most of the points in tutorial but still if you have any doubts then please let us know which point you are not getting.

      Regards,
      AndroidTutorialPoint Team

      • Hi Sir,
        Actually i want to learn how we get the Json data and how can we parse in to readable format…
        it’s very helpful if u add some More Comments so it will help me as i am new in Android

  2. Great Tutuorial. I’ve built this App like you tutored
    But Server key creating has been compromised by Google, I just can’t create it.
    I tried to using restrict key, but then i have to input specific ip address or websites,
    Please can you look into this.

    • This could be due to two reasons:

      1) Nearby police stations are not updated in Google Maps nearby your place.

      2) You are using invalid key. or API. Copy paste URL in Chrome browser. You will be able to see response coming from Google Server.

      All the best (y)

  3. Sir ,good job .This blog become the best for me .
    Can you add or send to me the diagram class to understand that clearly .
    Thank you .

  4. Hi Dhruv, are we using the same API KEY in the MapsActivity.java, google_maps_api.xml and AndroidManifest.xml. I still cannot display markers and (my current location(which is working a few days ago)).

  5. Hello Sir, I have a very basic question, where can I find a generate server key? I read several times this article to find whether I missed some thing, but still I can not find a way to generate server key . Your screen capture is exactly the same as mine, but still can not find a way to generate server key. Any suggestion? Thx in advance

  6. I was looking for same information but I was unable to find full tutorial.
    Finally, I reached here and get the full information which i wanted.
    Thank you

  7. Very helpful tutorial sir. I just wanted to ask if there is a way you could create an app in such a way that you can be able to add or rather see markers on the map where another device with the same app is located.In this case the markers are based on static locations available in google maps. What if i wanted to use my device to view and track the position of another device also having the same app installed? If you already made a tutorial on the same kindly direct me to it.

  8. This types of articles really help to make a next level android apps.

    I would say android tutorial point is one of the best place i have ever seen for android.

  9. Hi Team,
    I am new to android. I have a doubt here, where are we defining the distance within which google map will show its results?

  10. Very helpful tutorial sir. But i have a question then the app is good when i connected wifi. but when i disconnected, the app was terminated. And Log show this error :
    E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.nhat.testggmap, PID: 2705
    java.lang.NullPointerException: Attempt to invoke virtual method ‘int java.lang.String.length()’ on a null object reference
    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
    at org.json.JSONObject.(JSONObject.java:156)
    at org.json.JSONObject.(JSONObject.java:173)
    at com.example.nhat.testggmap.DataParser.parse(DataParser.java:24)
    at com.example.nhat.testggmap.GetNearbyPlacesData.onPostExecute(GetNearbyPlacesData.java:45)
    at com.example.nhat.testggmap.GetNearbyPlacesData.onPostExecute(GetNearbyPlacesData.java:19)
    at android.os.AsyncTask.finish(AsyncTask.java:660)
    at android.os.AsyncTask.-wrap1(AsyncTask.java)
    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
    So please tell me how can i fix it. I tried put if statement in DataParser.class then i want if jsonObject is null, app was do nothing and show a notification. but its not working.

  11. Hi, what key should be used inside the double quotes in the &key parameters? Should it be the same google map key you used for the fragment or you should make a new one?

  12. hi Sir,
    it’s a very nice tutorial ,
    But , ihave problem with “locationServices” => cannot resolve symbol LocationServices.
    Did anyone know what’s the problem!
    thank you.

  13. Hmm is anyone else encountering problems with the pictures on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the blog.

    Any suggestions would be greatly appreciated.

  14. Hello,

    very nice tutorial. I have downloaded the app and opened it using android studio. The map however does not appear. It simply remains a grey background with the buttons in the top left corner. Could anyone suggest why this is?

    Regards Dan

  15. hello sir,

    its great tutorial but i want to show school, hospital, atm, etc with icon without clicking button how its possible please help me.

    Thanks

  16. hello sir,
    its great tutorial but i want to show school, hospital, atm, etc with icon without clicking button how its possible please help me.

    Thanks

  17. Hi sir….. Nice tutorial….. I’m doing project based on this type…. Will u guide me sir….. Creating tourist app…. In this app gets the current location and display marker based on radius like 5km,20km,.. and also display particular places like lakes,church, park,..

  18. Hi sir….. Nice tutorial….. I’m doing project based on this type…. Will u guide me sir….. Creating tourist app…. In this app gets the current location and display marker based on radius like 5km,20km,.. and also display particular places like lakes,church, park,..

  19. not run program –
    error
    MapsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5273cb1c V.E….. R…..I. 0,0-684,426} that was originally added hereandroid.view.WindowLeaked: Activity urva.com.myapplication.MapsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5273cb1c V.E….. R…..I. 0,0-684,426} that was originally added here

  20. after running this codes i get this error

    Caused by: java.lang.NullPointerException
    at java.lang.VMClassLoader.findLoadedClass(Native Method)
    at java.lang.ClassLoader.findLoadedClass(ClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:499)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.support.v4.app.Fragment.isSupportFragmentClass(Fragment.java:469)
    at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2384)
    at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
    at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
    at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
    at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:77)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:754)
    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
    at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
    at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
    at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
    at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393) 
    at android.app.Activity.setContentView(Activity.java:2166) 
    at com.soundgodworld.hospitalproject.NearestHospital.onCreate(NearestHospital.java:61) 
    at android.app.Activity.performCreate(Activity.java:6237) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
    Application terminated.

  21. Hi Sir , This is one of the best tutorials point actually I am using the above code code is successfully running but map was not showing what is the problem please observe the below dependencies,

    dependencies {
    compile fileTree(dir: ‘libs’, include: [‘*.jar’])
    testCompile ‘junit:junit:4.12’
    compile ‘com.android.support:appcompat-v7:24.2.1’
    compile ‘com.google.android.gms:play-services:10.0.1’
    }

  22. I have subscribed to your newsletter and I downloaded the full code and loaded into android studio. It compiled allright, but it showed a blank screen with three buttons:

    NEARBY RESTAURANTS
    NEARBY HOSPITALS
    NEARBY SCHOOLS.
    A toast indicating “Your Current Location”appeared, but no data.

  23. I am getting this exception…

    java.lang.ClassNotFoundException: Didn’t find class “com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader”

    Can you help in figuring out where i am doing things wrong

  24. ont un dessus en daim gris et canvas gris clair contrastes par du cuir bleu a motif argente style safari, par un swoosh en cuir peche et une semelle exterieure en gum.La pair

  25. I got this error. please help me.
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roshan.maproute/com.example.roshan.maproute.MapsNewActivity}: android.view.InflateException: Binary XML file line #4: Error inflating class fragment

  26. Thank you for the nice tutorial sir…:)

    What are the key word i need to use to find Petrol station, Police station, Workshop,

    String url = getUrl(latitude, longitude, Parks);

  27. Thank you for the nice tutorial sir…:)

    What are the names i need to use to find near by Petrol station, Police station, Workshop, etc…?

  28. Hi I’ve followed everything to what I think is exact but I’m getting this message when clicking the button:

    “error_message” : “This IP, site or mobile application is not authorized to use this API key. Request received from IP address 81.97.249.79, with empty referer”,
    “html_attributions” : [],
    “results” : [],
    “status” : “REQUEST_DENIED”

  29. I am really thankful to the holder of this web site who has shared this
    great paragraph at here.

  30. Nice tutorial. thumbs up! 😀
    Do you have other tutorials that instead of buttons to be click it will be the list view (ex. inside the list view: ATM, BANK, RESTAURANT).

  31. Sorry, why my app is not working when i click the nearby restaurant, hospital or school. anyone have the same problem ?

  32. Please let me know if you’re looking for a writer for your weblog.
    You have some really great articles and I believe I would
    be a good asset. If you ever want to take some of the load off, I’d love to write
    some content for your blog in exchange for a link back to mine.
    Please shoot me an email if interested. Thank you!

  33. I am very glad for your code but i am facing problem with the maps api with error called OVER_QUERY_LIMIT

    can you help in providing solution

  34. I have one issue. I have run the code in android studio and it is running fine but if I want to search for Healthy food instead of restaurant but it still showing the restaurants, where should I change so it show me Healthy food.

    Apart from that sometime it shows the result sometimes it doesn’t show anything,Would you help me with that.

  35. hi…nice tutorial…but there is a question, what string should be passed if I want to know the number of vehicles around user’s current location

    • can you please elaborate the question?
      Because in my understanding its displaying the tagged result of google. So how can we find no of vehicles.Strange

  36. i want to ask is i have to add the Current location code to it or use the same code of it.And if i use the current location code then will i need to use the same server key or different server key.

  37. Hi , it is a great tutorial. It worked for the first time i tried to run and after which it says “”You have exceeded your daily request quota for this API.” with status OVER_QUERY_LIMIT. Would be really helpful if you can help me resolve it. Thanks.

  38. Hi i am sanjay , when i run the code the maps are displayed gray. can any one suggest a solution for this.

  39. android_map.xml is not working for me. “Element FrameLayout don’t have required layout_height attribute” error like this is showing

  40. Very Nice App and easy to understand. Sir, in my app i find to get the phone number or mobile number of nearby places. So, how i get the mobile\phone number of nearby places ? please help me sir

  41. Hey
    Im stuck with the activity_maps.xml file
    Could somebody please send the complete code under activity_maps.xml file.

  42. Broo, thank you for your tutorial. This is very meaningfull for me. I want ask you, what if nearby searching is finding other user which is use same aplication so they can know location by each others in google maps? Is it possible? Should i make database to get latitude and longtitude from every user which is registered? Please help, bro. Thank tou.

  43. Hi! Thank you for the code.
    However, when I launch my app, it terminates immediately with the message ‘Unfortunately your app has stopped’. I can’t figure out where the problem is. Can you please help me?

  44. Hi, thankyou for your code. Very informative!
    I followed your tutorial step by step. However, when I launched my app, it immediately terminated with the message ‘Unfortunately, your app has stopped’. I can’t figure out the reason. Please help me out!

  45. Attempt to invoke virtual method ‘int org.json.JSONArray.length()’ on a null object reference
    can anyone suggestion to solve

  46. java.lang.NullPointerException: Attempt to invoke virtual method ‘int org.json.JSONArray.length()’ on a null object reference.

    anyone can suggestion me to solve it.

  47. Thanku Sir for such a helpful tutorial.But I have a doubt. I am making an app in which user can find near by doctors like gayenacologist,dentist,physician,nutritionist and many more. How can I find these varieties of doctors? Please help me out from this problem ASAP.
    ThankYou 🙂

  48. Thankyou sir for such a helpful tutorial. But I am getting one problem. When i click on hospitals/school my app is unfortunately getting stop.Only the toast message is generated. I am working on a project.So,plz help me out from this trouble .
    Thank you!!

  49. i want to add this near by resturent button on main Activity and when we click on that button then it find all near by resturent on googlemap activity.

    please help me how to do this?

  50. Hello. I downloaded the code and in that change it to my API key as well. I’m not getting any errors but the problem is I’m not able to see the map on my screen. The map screen shows in grey color and the buttons are visible and clickable but still cannot see map on my screen. It will be great if someone can provide me with the solution as soon as possible. Thanks

  51. I have problem in maps_activity layout there are also mentioned layout_height and width attribute but error occur defined layout height and width attribute

Leave a Reply

Advertisment ad adsense adlogger