Main navigation

Google Maps Nearby Places API using Retrofit Android



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. Also if you don’t want to learn Retrofit then you can refer our tutorial of Google Maps Search Nearby where we have used Async Task to implement exactly same tutorial.

Creating new project

Please follow following steps:

  1. Open Android Studio and make a new project with name “Google Maps Retrofit” or “Google Maps Nearby Places API” and company domain (I used my company domain i.e 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. (…/GoogleMapsSearchNearby/app/src/main/java/com/androidtutorialpoint/googlemapssearchnearby
  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 Nearby Places API

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 Nearby Places API

Click on Server Key. Below screen will appear:

Google Maps Nearby Places API

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.


    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:

    You can also add your credentials to an existing key, using this line:

    Alternatively, follow the directions here:

    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>     

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


<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.androidtutorialpoint.googlemapsdrawroute"

         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=""/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


             The API key for Google Maps Nearby Places API 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/. 

                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>


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:



    <fragment android:id="@+id/map"

    <LinearLayout xmlns:android=""

        android:text="Nearby Restaurants" />

        android:text="Nearby Hospitals" />

        android:text="Nearby Schools" />

        android:layout_height="wrap_content" />

        android:layout_height="wrap_content" />


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

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile ''
    compile ''
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile ''
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
    compile 'com.squareup.okhttp:okhttp:2.4.0'


Fourth line compile ‘’ is responsible for inserting Google Play Services. Please make sure this line is present in build.gradle. Remaining lines after 4th line are responsible for adding Retrofit Android library files. Sync the Project.

Implementation of Google Maps using Retrofit

To make it clear we first have to see how URL of Google Maps Nearby Places API is implemented. Click on following link:

Google Maps Nearby Places Using Retrofit

This is what will return by Google Server while we search for nearby places around current location of user. As you could see in the link we have JSON Object and Array as data returned from Google Maps. We have to capture this data in our App and accordingly add marker at each location. To capture this data using Retrofit Android, we have to make POJO Class. This class is actually composed of Getter and Setter methods.

Adding POJO Class

Add following classes in a separate folder named POJO at path …/GoogleMapsRetrofit/app/src/main/java/com/androidtutorialpoint/googlemapsretrofit/POJO

File structure will finally look like this:

Google Maps Nearby Places API Files

These POJO classes will be used to get data from URL from its “get” functions. We will see this later.

Interface Declaration

Make a new interface named and add following code:

package com.androidtutorialpoint.googlemapsretrofit;

import com.androidtutorialpoint.googlemapsretrofit.POJO.Example;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Query;

 * Created by navneet on 17/7/16.
public interface RetrofitMaps {

     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    Call<Example> getNearbyPlaces(@Query("type") String type, @Query("location") String location, @Query("radius") int radius);


Let’s have a look at above interface. @GET is used to call server (corresponding to URL). It is predefined part of Retrofit android library, only end part of URL will be added here. Here we have added key and sensor as part of the URL while rest of the variable (like location and radius) will be passed at run time using Query in getNearbyPlaces(). getNearbyPlaces method is used to get details of the points returned from Google Server and Example is a POJO class to store that response. One more point to note down here is location coordinates passed in getNearbyPlaces will be current location of the user as we will see later. Corresponding to these coordinates, Google will return nearby places location. Code of Google Maps Search Nearby App

As you know, this is heart of our Google Maps Nearby Places API and hence it needs special attention. Here we will first build Retrofit and then will add Markers at the points returned by getter methods of POJO Class. Here we won’t discuss code related to getting current user location. You can get that information here.

First of all, we will check if Google Play Services available or not in onCreate() function of For that we will use function 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,
            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 most important part of our Google Maps Nearby Places API code i.e. onMapReady() function. Here we will first build a Google API Client and then enable current user location using mMap.setMyLocationEnabled(true).


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

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(;
        btnRestaurant.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

Build Retrofit and add Markers

Here we will build Retrofit and add markers at the points returned by Google Server. Add following code in function build_retrofit_and_get_response().

private void build_retrofit_and_get_response(String type) {

        String url = "";

        Retrofit retrofit = new Retrofit.Builder()

        RetrofitMaps service = retrofit.create(RetrofitMaps.class);

        Call<Example> call = service.getNearbyPlaces(type, latitude + "," + longitude, PROXIMITY_RADIUS);

        call.enqueue(new Callback<Example>() {
            public void onResponse(Response<Example> response, Retrofit retrofit) {

                try {
                    // This loop will go through all the results and add marker on each location.
                    for (int i = 0; i < response.body().getResults().size(); i++) {
                        Double lat = response.body().getResults().get(i).getGeometry().getLocation().getLat();
                        Double lng = response.body().getResults().get(i).getGeometry().getLocation().getLng();
                        String placeName = response.body().getResults().get(i).getName();
                        String vicinity = response.body().getResults().get(i).getVicinity();
                        MarkerOptions markerOptions = new MarkerOptions();
                        LatLng latLng = new LatLng(lat, lng);
                        // Position of Marker on Map
                        // Adding Title to the Marker
                        markerOptions.title(placeName + " : " + vicinity);
                        // Adding Marker to the Camera.
                        Marker m = mMap.addMarker(markerOptions);
                        // Adding colour to the marker
                        // move map camera
                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());

In the above code we build Retrofit using Retrofit.Builder() and converted JSON data into accessible data object using GsonConverterFactory. You can read more about GSON. After this we passed our interface RetrofitMaps to the retrofit to get details of the nearby places. Now comes the last but most important part i.e. Executing call and adding marker on each point on Google Maps Nearby Places API.
Calls may be executed synchronously with execute(), or asynchronously with enqueue(). enqueue() will Asynchronously send the request and notify callback of its response or if an error occurred talking to the server, creating the request, or processing the response. If response comes then onResponse will be automatically called. If response doesn’t come out then onFailure will be called and reason of failure will be printed.
While calling getNearbyPlaces we are passing latitude and longitude coordinates of current location of user. Also PROXIMITY_RADIUS is provided to search nearby places only under that radius. After getting response from server onResponse is called automatically. In this method we first cleared Google Maps using mMap.clear() so that any pre-deposited markers are deleted. Then a loop is initiated to get every nearby place and one by one marker is added at each location. We get the coordinates of nearby places through getter methods defined in POJO Classes. For Example to get the longitude and latitude we used getLat() and getLng() from

So finally our tutorial of Google Maps Nearby Places API is complete. You can see full code of here:

We would suggest you to turn on GPS and Internet Connection. Run this Google Maps Nearby Places API on any real 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

You can see demo of Google Maps Nearby Places API in the Youtube video given at the start of tutorial. We have tried to explain each and every step but still if you have any doubt then please comment. Also we are open to suggestions of any future tutorials. All the best 🙂 .

What’s Next

You can now learn how to draw a route on Google Maps between any two location. 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


      • hey i want to find the location of other users on same a…
        like 5-6 users have the same a and are standing at different locations or or even cities… i want to display the marker and rout to every user in app… is it possible??
        if yes please help….

  1. hi sir, all ur’s tutorial based on get method will u please post other methods like field and querymap in retrofit library

    • Yeah you are right. Most of our tutorials on Retrofit are using GET method. We will surely make a new one using POST method. Stay tuned !!

  2. nice tutorial sir, can you share tutorial about show marker polyline with getting data from json mysql?
    thank you

      • cannot resolve method ‘getGeometry()’
        cannot resolve method ‘getName()’
        cannot resolve method ‘getVicinity()’

        i also notice that most methods in the classes in the POJO file are ‘never used’ for instance in the class i get such ‘method getOpenNow()’ is never used, ”method getWidth() is never used’ in the class among many others……

        i am thinking most of those methods not being used might be the cause of the above errors

    • hi George, i’m also experiencing the same problem and going through the comments i saw you had the same problem as well so if you found a way around it please share

  3. 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.

  4. How did you get the API key to activate the google places api? I can’t seem to connect my api key to use the google places api.. the same key I used in the map is not able to display the nearby places. help..

  5. whoah this blog is magnificent i love studying your posts.
    Keep up the good work! You realize, many people are hunting round for this info, you could help them greatly.

  6. This is awesome, works really well. Could you please make a tutorial on how to fetch location coordinates from a database and displaying them on the map. I tried it by making some tweaks on this code and changing the String url. The app seems to be working well but no markers are added when i run it. I am guessing the problem is server communication or maybe the json string i am parsing is in wrong format.

  7. Hi, the retrofit call isnt returning any nearby search result, is there any updated tutorial to shared? urgent here. Thanks in advanced

  8. I like ur post ….
    the current user location work well … but it doesnt work on nearby location
    can u give me some guild on that ?

  9. hi, great tutorial. it works well on my device, and currently i’m trying to put the results of nearby restaurants into a list view.
    can you help me with this? anyone?
    a reply would be really appreciated, thanks in advance.

  10. it works well, but do you know how to put the results into a listview? anyone can help me with this?
    thanks in advance

  11. i want to find the location of 5-6 user using the same app..
    like these user are standing at different places or even in different cities.. i want to display all the users with marker and a minimum rout to all users.. not in one specific app but in all user’s apps… Basically the idea is to find all the users… please help

  12. mGoogleApiClient error in mainactivity
    Call call = service.getNearbyPlaces(type, latitude + “,” + longitude, PROXIMITY_RADIUS);
    lat and long and proximity error

    please help to resolve ot

  13. If i want use this tutorial for search place based on my own database mysql, is it possible with retrofit? Can you help me please? thx

Leave a Reply

Advertisment ad adsense adlogger