Google Maps Nearby Places API using Retrofit Android

Skip links

Main navigation

Google Maps Nearby Places API

Hello Guys. Hope all of you are doing well. In this tutorial, we will learn how to add the markers on nearby places in Google Maps API using . We will name this App as Google Maps Nearby Places API. You can see demo of this tutorial in above video. This is one of the most crystal clear tutorials where minimum code is used to implement nearby places app using retrofit. We made a similar tutorial on

but that was implemented using Async Task. Now Async task has become pretty much mediocre and people are using Retrofit to capture data from URL, So we made this tutorial on similar lines. Now you don’t have to make any JSON Parser or Data capture class. Retrofit Android automatically takes care of it. All the people who do not know how to use Retrofit Android can see our tutorial of .

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it .

2) A real time android device (Smartphone or Tablet) .

3) A basic knowledge of

& functions used in Android Studio.

Before going through this post we will suggest you to first have a look at our post on . That information (inside link) will be used in this post.

Now let’s make it. We hope you would have already made an . So we are not repeating that part now. Also if you don’t want to learn Retrofit then you can refer our tutorial of

where we have used Async Task to implement exactly same tutorial.

Please follow following steps:

Open Android Studio and make a new project with name “Google Maps Retrofit” or “Google Maps Nearby Places API” 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. Again Click Next and Choose Google Maps Activity

(as shown in following pic).

Leave all things remaining same and Click Finish.

Now you will be able to see three files:

google_maps_api.xml (…/GoogleMapsSearchNearby/app/src/debug/res/values/google_maps_api.xml)

MapsActivity.java (…/GoogleMapsSearchNearby/app/src/main/java/com/androidtutorialpoint/googlemapssearchnearby

/MapsActivity.java)

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.

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

Click on Go to credentials. Below screen will appear.

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:

Click on Server Key. Below screen will appear:

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

LVwrKoLOEMgwUBXGiut0bkFhoAjOiaVemoMlymg

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

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 . Refer below code:

activity_maps.xml

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 ‘com.android.support:appcompat-v7:23.1.1’

compile ‘com.google.android.gms:play-services:8.4.0’

compile ‘com.squareup.retrofit:retrofit:2.0.0-beta2’

compile ‘com.google.code.gson:gson:1.7.2’

compile ‘com.squareup.retrofit:converter-gson:2.0.0-beta2’

compile ‘com.squareup.okhttp:okhttp:2.4.0’

}

Fourth 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. Remaining lines after 4th line are responsible for adding Retrofit Android library files. Sync the Project.

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

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:

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 RetrofitMaps.java 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.

*/

@GET(“api/place/nearbysearch/json?sensor=true&key=AIzaSyDN7RJFmImYAca96elyZlE5s_fhX-MMuhk”)

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

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 .

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

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

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 . 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() {

@Override

public void onClick(View v) {

build_retrofit_and_get_response(“restaurant”);

}

});

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 = “https://maps.googleapis.com/maps/”;

Retrofit retrofit = new Retrofit.Builder()

.baseUrl(url)

.addConverterFactory(GsonConverterFactory.create())

.build();

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

Call call = service.getNearbyPlaces(type, latitude + “,” + longitude, PROXIMITY_RADIUS);

call.enqueue(new Callback() {

@Override

public void onResponse(Response response, Retrofit retrofit) {

try {

mMap.clear();

// 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 MapmarkerOptions.position(latLng);// Adding Title to the MarkermarkerOptions.title(placeName + " : " + vicinity);// Adding Marker to the Camera.Marker m = mMap.addMarker(markerOptions);// Adding colour to the markermarkerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));// move map cameramMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));mMap.animateCamera(CameraUpdateFactory.zoomTo(11));}} catch (Exception e) {Log.d("onResponse", "There is an error");e.printStackTrace();}}@Overridepublic 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 . 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 Location.java.So finally our tutorial of Google Maps Nearby Places API is complete. You can see full code of MainActivity.java 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: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 🙂 .You can now learnbetween any two location. We have made a distance calculator app too, have a look at it here: .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 ourPage or Add us on . Happy Coding 🙂You can download full code belowReader InteractionsThat’s really very nice post.Nice tutorial. I’m looking for more tutorials about Retrofit.hi,could u pls share the tutorial for post parameters using retrofithi sir, all ur’s tutorial based on get method will u please post other methods like field and querymap in retrofit libraryHi,,,thank u for ur response.nice tutorial sir, can you share tutorial about show marker polyline with getting data from json mysql?thank youThat was really nice post.!Thank youi get an error with getGeometry (),getname() and getVicinity()Your video is very helpful in such cases where you have to do entire process by itself.Thank youthe key in the retrofit interface, it it the key which i generated?the process of setting up the server key is not working. Where can i create the server key?Your every articles on google maps are wonderful and worth reading.Keep sharing!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.Good step by step information.Clean and understandable code.Good job.thanks for this awesome post Sir! It helped me a lot in my project 🙂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..Can we also show the list of the nearby places if yes then please let me know how.I want get all result of api , I know it has 60 results, Help me?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.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.Hi, the retrofit call isnt returning any nearby search result, is there any updated tutorial to shared? urgent here. Thanks in advancedIt is really veryhelpful ….as a beginner i find it very easily understandable;well elaborated.I like ur post ….the current user location work well … but it doesnt work on nearby locationcan u give me some guild on that ?I get an error on getgeometry too!!!Primary SidebarFooter

Read More Post