<p>The Google Play Services version of the Places SDK for Android (i.e. <strong><span style="color: #008000;">com.google.android.gms:play-services-places</span></strong>) is turned off on July 29, 2019. Now a new version of the Places SDK for Android is available which depends on <span style="color: #0000ff;"><strong><span style="color: #008000;"><a style="color: #008000;" href="https://developer.android.com/jetpack/androidx">AndroidX</a></span>.</strong></span></p>
<p>In this article, we will talk about how to get current and nearby places of user&#8217;s device using a new Google Places library and also how to implement it in google map.</p>
<p>The new version of the Places SDK for Android introduces new methods :</p>
<p><strong><span style="color: #0000ff;">fetchPlace()</span></strong> : Fetches the details about a particular place.</p>
<p><strong><span style="color: #0000ff;">fetchPhoto()</span> </strong>: Fetches a photo. The photos service may cache the image data. If the requested photo does not exist in the cache then a network lookup will be performed.</p>
<p><strong><span style="color: #0000ff;">findCurrentPlace()</span> </strong>: Fetches the approximate current location of the user&#8217;s device. It returns a list of <strong><span style="color: #008000;">PlaceLikelihoods</span></strong> indicating places where the user&#8217;s device is most likely to be located.</p>
<p><strong><span style="color: #0000ff;">findAutocompletePredictions()</span></strong> : It return place predictions in response to user search queries.</p>
<h3 id="install_the_client_library"><span style="color: #000080;"><strong>Adding the client library</strong></span></h3>
<p>In the <strong><span style="color: #008000;">dependencies</span></strong> section of your app-level <strong><span style="color: #0000ff;">build.gradle</span></strong> file, add a dependency for the new SDK client library, as shown below:</p>
<pre class="notranslate" dir="ltr"><span class="pln">dependencies </span><span class="pun">{</span><span class="pln">
 implementation </span><span class="str">'com.google.android.libraries.places:places:2.0.0'</span>
<span class="pun">}</span></pre>
<p>Make sure that the <strong><span style="color: #008000;">minSdkVersion</span></strong> for your application project is 16 or higher</p>
<h3 id="initialize_the_new_places_sdk_client"><strong><span style="color: #000080;">Initialize the new Places SDK client</span></strong></h3>
<p>Initialize the new Places SDK client as shown below:</p>
<pre dir="ltr"><code dir="ltr"><span class="com"><strong><span style="color: #008000;">// Add an import statement for the client library.</span></strong></span>
<span class="kwd">import</span><span class="pln"> com</span><span class="pun">.</span><span class="pln">google</span><span class="pun">.</span><span class="pln">android</span><span class="pun">.</span><span class="pln">libraries</span><span class="pun">.</span><span class="pln">places</span><span class="pun">.</span><span class="pln">api</span><span class="pun">.</span><span class="typ">Places</span><span class="pun">;</span>

<span class="pun">...</span>

<strong><span class="com" style="color: #008000;">// Initialize Places.</span></strong>
<span class="typ">Places</span><span class="pun">.</span><span class="pln">initialize</span><span class="pun">(</span><span class="pln">getApplicationContext</span><span class="pun">(),</span><span class="pln"> apiKey</span><span class="pun">);</span>

<strong><span class="com" style="color: #008000;">// Create a new Places client instance.</span></strong>
<span class="typ">PlacesClient</span><span class="pln"> placesClient </span><span class="pun">=</span> <span class="typ">Places</span><span class="pun">.</span><span class="pln">createClient</span><span class="pun">(</span><span class="kwd">this</span><span class="pun">);</span></code></pre>
<p>Now let’s see how to implement this in an example project.</p>
<h3><span style="color: #000080;"><strong>Creating New Project</strong></span></h3>
<p><strong>1</strong> .Create a new project in <span style="color: #008000;"><strong>Android Studio</strong></span> from <span style="color: #008000;"><strong>File ⇒ New Project</strong></span> and fill the project details.</p>
<h4><span style="color: #000080;"><strong>Getting the API key</strong></span></h4>
<ul>
<li>Go to <span style="color: #0000ff;"><strong>Google API Console.</strong></span></li>
<li>Create a new project and generate a new API key corresponding to your <span style="color: #008000;"><strong>SHA1</strong></span> and <span style="color: #008000;"><strong>application package name</strong></span>.</li>
<li>To integrate google map and to access nearby places in your application<span style="color: #0000ff;"><span style="color: #000000;"> </span></span>enable <strong><span style="color: #008000;">Maps SDK for Android</span></strong> and <span style="color: #008000;"><strong>Places API.</strong></span></li>
<li>Open <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> and add the generated API key to your project above the application <span style="color: var(--color-text);">tag as shown below :</span></li>
</ul>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span><!--?xml version="1.0" encoding="utf-8"?--></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getnearbyplaces">;

<;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />;
<;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>;
<;uses-permission android:name="android.permission.INTERNET"/>;

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

 <;activity android:name=".MainActivity">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

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

 <strong><span style="color: #008000;"> <;meta-data</span></strong>
<strong><span style="color: #008000;"> android:name="com.google.android.geo.API_KEY"</span></strong>
<strong><span style="color: #008000;"> android:value="@string/API_KEY" />;</span></strong>

<;/application>;

<;/manifest>;</pre>
<p><strong>2</strong>. Open <span style="color: #008000;"><strong>build.gradle</strong></span> and add dependency for the new Places SDK client library to get current and nearby places and also add a dependency for google map as shown below:</p>
<p><span style="color: #0000ff;"><strong>build.gradle</strong></span></p>
<pre>dependencies {
 implementation fileTree(dir: 'libs', include: ['*.jar'])
 implementation 'androidx.appcompat:appcompat:1.1.0'
 implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
<span style="color: #008000;"><strong>
 //library for google map</strong></span>
 implementation 'com.google.android.gms:play-services-maps:16.1.0'
<span style="color: #008000;"><strong>
 //Places SDK client library</strong></span>
 implementation 'com.google.android.libraries.places:places:2.0.0'

 testImplementation 'junit:junit:4.12'
 androidTestImplementation 'androidx.test:runner:1.2.0'
 androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}</pre>
<p><strong>3 </strong>.Open <span style="color: #008000;"><strong>AndroidManifest</strong></span> file and add all the permissions which you want to request above the application tag.</p>
<p><span style="color: #0000ff;"><strong>AndroidManifest.xml</strong></span><!--?xml version="1.0" encoding="utf-8"?--></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getnearbyplaces">;

<strong><span style="color: #008000;"><;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />;</span></strong>
<strong><span style="color: #008000;"><;uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>;</span></strong>
<strong><span style="color: #008000;"><;uses-permission android:name="android.permission.INTERNET"/>;</span></strong>

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

 <;activity android:name=".MainActivity">;
 <;intent-filter>;
 <;action android:name="android.intent.action.MAIN" />;

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

 <;meta-data
 android:name="com.google.android.geo.API_KEY"
 android:value="@string/API_KEY" />;

<;/application>;

<;/manifest>;</pre>
<p><strong>4</strong>. Open the layout file of your main activity (<span style="color: #008000;"><strong>activity_main.xml</strong> </span>). Now add map fragment to show map and one button to get nearby places.</p>
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong> </span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">;

 <;Button
 android:id="@+id/btn_nearby_places"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentBottom="true"
 android:layout_margin="16dp"
 android:background="@color/colorPrimary"
 android:text="Find NearBy Places"
 android:textColor="#FFFFFF"
 android:textStyle="bold" />;

 <;fragment
 android:id="@+id/map"
 android:name="com.google.android.gms.maps.SupportMapFragment"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />;

<;/RelativeLayout>;</pre>
<h4 id="initialize_the_new_places_sdk_client"><strong><span style="color: #000080;">Initialize the new Places SDK client</span></strong></h4>
<p><strong>5 </strong>.Open <span style="color: #008000;"><strong>MainActivity.java</strong></span> and inside onCreate() initialize the new Places SDK client as shown below:</p>
<pre>@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 <strong><span style="color: #008000;">// Initialize Places.</span></strong>
 Places.initialize(getApplicationContext(), "AIzaSyCMznC3Jp0dQQTqLkq15qnz-U-kDA2_pHo");

 <strong><span style="color: #008000;">// Create a new Places client instance.</span></strong>
 placesClient = Places.createClient(this);
}</pre>
<h4><strong><span style="color: #000080;">Finding Current Location</span></strong></h4>
<p>Places SDK library provide a method called <strong><span style="color: #008000;"><a style="color: #008000;" href="https://developers.google.com/places/android-sdk/reference/com/google/android/libraries/places/api/net/PlacesClient.html#findCurrentPlace(com.google.android.libraries.places.api.net.FindCurrentPlaceRequest)">findCurrentPlace()</a></span></strong> to find the current location of the user&#8217;s device.It returns a list of <strong><span style="color: #008000;">PlaceLikelihoods</span></strong> indicating places where the user&#8217;s device is most likely to be located.</p>
<p><strong>6 </strong>.Create a <strong><span style="color: #008000;">FindCurrentPlaceRequest</span></strong>, including a list of place data types to return.</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<pre dir="ltr"><code dir="ltr"><span class="com"><strong><span style="color: #008000;">// Use fields to define the data types to return.</span></strong></span><span class="pln">
 </span><span class="typ">List</span><span class="pun"><;</span><span class="typ">Place</span><span class="pun">.</span><span class="typ">Field</span><span class="pun">>;</span><span class="pln"> placeFields </span><span class="pun">=</span> <span class="typ">Arrays</span><span class="pun">.</span><span class="pln">asList</span><span class="pun">(<span class="typ">Place</span>.<span class="typ">Field</span>.<span class="pln">ID,
</span></span><span class="typ">Place</span><span class="pun">.</span><span class="typ">Field</span><span class="pun">.</span><span class="pln">NAME,<span class="typ">Place</span><span class="pun">.</span><span class="typ">Field</span><span class="pun">.</span>ADDRESS</span><span class="pun">);</span><span class="pln">

 </span><strong><span class="com" style="color: #008000;">// Use the builder to create a FindCurrentPlaceRequest.</span></strong><span class="pln">
 </span><span class="typ">FindCurrentPlaceRequest</span><span class="pln"> request </span><span class="pun">=</span><span class="pln">
 </span><span class="typ">FindCurrentPlaceRequest</span><span class="pun">.</span><span class="pln">builder</span><span class="pun">(</span><span class="pln">placeFields</span><span class="pun">).</span><span class="pln">build</span><span class="pun">();</span></code></pre>
<p><strong>7 </strong>.Call <strong><span style="color: #008000;">findCurrentPlace</span></strong> and handle the response, checking first to verify that the user has granted permission to use their device location.</p>
<pre>if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

 placesClient.findCurrentPlace(request).addOnCompleteListener(new OnCompleteListener() {
 @Override
 public void onComplete(@NonNull Task task) {

 if (task.isSuccessful()) {

 FindCurrentPlaceResponse response = task.getResult();
 placeLikelihoods = new ArrayList<;>;();
 placeLikelihoods.addAll(response.getPlaceLikelihoods());

 <strong><span style="color: #008000;">//response.getPlaceLikelihoods() will return list of PlaceLikelihood
 //we need to create a custom comparator to sort list by likelihoods</span></strong>
 Collections.sort(placeLikelihoods, new Comparator() {
 @Override
 public int compare(PlaceLikelihood placeLikelihood, PlaceLikelihood t1) {
 return new Double(placeLikelihood.getLikelihood()).compareTo(t1.getLikelihood());
 }
 });

 <strong><span style="color: #008000;">//After sort ,it will order by ascending , we just reverse it to get first item as nearest place
</span> </strong> Collections.reverse(placeLikelihoods);

 placeId = placeLikelihoods.get(0).getPlace().getId();
 latLng = placeLikelihoods.get(0).getPlace().getLatLng();
 address = placeLikelihoods.get(0).getPlace().getAddress();

 <strong><span style="color: #008000;">//Removing item of the list at 0 index</span></strong>
 placeLikelihoods.remove(0);

 SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 supportMapFragment.getMapAsync(MainActivity.this);

 }

 }
 }).addOnFailureListener(new OnFailureListener() {
 @Override
 public void onFailure(@NonNull Exception e) {

 Toast.makeText(MainActivity.this, "Place not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
 }
 });
} else {

 <strong><span style="color: #008000;">//Requesting permission if it is not already granted</span></strong>
 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
 return;
}
</pre>
<h4><strong><span style="color: #000080;">Complete Code</span></strong></h4>
<p><strong>8 </strong>.Open <span style="color: #008000;"><b>MainActivity.java</b></span> and write the below code.</p>
<p><span style="color: #0000ff;"><b>MainActivity.java</b></span></p>
<pre>package com.example.getnearbyplaces;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.PlaceLikelihood;
import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest;
import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse;
import com.google.android.libraries.places.api.net.PlacesClient;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

 private static final int REQUEST_CODE = 200;
 PlacesClient placesClient;
 List placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS);
 Button btn_nearby_places;
 LatLng latLng;
 String address;
 private String placeId;
 private List placeLikelihoods;
 GoogleMap map;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 <strong><span style="color: #008000;">// Initialize Places.</span></strong>
 Places.initialize(getApplicationContext(), "AIzaSyCMznC3Jp0dQQTqLkq15qnz-U-kDA2_pHo");

 <strong><span style="color: #008000;">// Create a new Places client instance.</span></strong>
 placesClient = Places.createClient(this);

 btn_nearby_places = findViewById(R.id.btn_nearby_places);

 <strong><span style="color: #008000;">//Get the current place and nearby places of your device</span></strong>
 getCurrentPlace();

 btn_nearby_places.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {

 <strong><span style="color: #008000;">//setting Marker at nearby places</span></strong>
 setMarkerAtNearbyPlaces();
 }
 });
 }

 private void getCurrentPlace() {

 FindCurrentPlaceRequest request =
 FindCurrentPlaceRequest.builder(placeFields).build();

 <strong><span style="color: #008000;">// Call findCurrentPlace and handle the response (first check that the user has granted permission).</span></strong>
 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

 placesClient.findCurrentPlace(request).addOnCompleteListener(new OnCompleteListener() {
 @Override
 public void onComplete(@NonNull Task task) {

 if (task.isSuccessful()) {

 FindCurrentPlaceResponse response = task.getResult();
 placeLikelihoods = new ArrayList<;>;();
 placeLikelihoods.addAll(response.getPlaceLikelihoods());

 <strong><span style="color: #008000;">//response.getPlaceLikelihoods() will return list of PlaceLikelihood</span></strong>
<strong><span style="color: #008000;"> //we need to create a custom comparator to sort list by likelihoods</span></strong>
 Collections.sort(placeLikelihoods, new Comparator() {
 @Override
 public int compare(PlaceLikelihood placeLikelihood, PlaceLikelihood t1) {
 return new Double(placeLikelihood.getLikelihood()).compareTo(t1.getLikelihood());
 }
 });

 <strong><span style="color: #008000;">//After sort ,it will order by ascending , we just reverse it to get first item as nearest place</span></strong>
 Collections.reverse(placeLikelihoods);

 placeId = placeLikelihoods.get(0).getPlace().getId();
 latLng = placeLikelihoods.get(0).getPlace().getLatLng();
 address = placeLikelihoods.get(0).getPlace().getAddress();

 <strong><span style="color: #008000;">//Removing item of the list at 0 index</span></strong>
 placeLikelihoods.remove(0);

 SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
 supportMapFragment.getMapAsync(MainActivity.this);
 }


 }
 }).addOnFailureListener(new OnFailureListener() {
 @Override
 public void onFailure(@NonNull Exception e) {

 Toast.makeText(MainActivity.this, "Place not found: " + e.getMessage(), Toast.LENGTH_LONG).show();
 }
 });
 } else {

 <strong><span style="color: #008000;">//Requesting permission if it is not already granted</span></strong>
 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
 return;
 }

 }

 private void setMarkerAtNearbyPlaces() {

 for (PlaceLikelihood place : placeLikelihoods) {

 MarkerOptions markerOptions = new MarkerOptions().position(place.getPlace().getLatLng()).title(place.getPlace().getAddress());

 map.addMarker(markerOptions);
 }

 }

 @Override
 public void onMapReady(GoogleMap googleMap) {
 map = googleMap;

 <strong><span style="color: #008000;">//Adding marker in map at current location</span></strong>
 MarkerOptions markerOptions = new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
 googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
 googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
 googleMap.addMarker(markerOptions);
 }

 <strong><span style="color: #008000;">//handling request permission response</span></strong>
 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

 switch (requestCode) {
 case REQUEST_CODE:

 if (grantResults.length >; 0 &;&; grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
 getCurrentPlace();
 } else
 Toast.makeText(this, "Permission denied", Toast.LENGTH_LONG).show();
 break;
 }
 }

}</pre>


