- Published on
Finding Nearby Businesses and Services on Android
- Authors
- Name
- how-to.digital
Finding Nearby Businesses and Services on Android
In this tutorial, we will learn how to use Android's location services to find nearby businesses and services. We will be leveraging the Google Places API to fetch relevant data and display it on our Android app.
Requirements
To follow along with this tutorial, you will need:
- Android Studio installed on your machine
- An Android device or emulator with internet connectivity
Setting up the project
- Open Android Studio and create a new project.
- Choose an appropriate name for your project and select the minimum SDK version that matches your target audience.
- Click "Next" and choose "Empty Activity" as the template.
- Click "Finish" to create the project.
Configuring the Google Places API
Before we can start using the Google Places API, we need to create an API key.
- Go to the Google Cloud Console.
- Create a new project or select an existing one from the dropdown menu at the top.
- Click on the "Enable APIs and Services" button.
- In the search bar, type "Places API" and select it from the results.
- Click the "Enable" button for the Places API.
- Go back to the Dashboard and click on the "Credentials" tab.
- Click on the "Create Credentials" button and select "API key" from the dropdown menu.
- Copy the generated API key.
Adding the Google Places API dependency
To integrate the Google Places API into our Android project, we need to add the necessary dependency.
Open your project's
build.gradle
file.Inside the
dependencies
block, add the following line:implementation 'com.google.android.gms:play-services-places:<version>'
Replace
<version>
with the latest version of the Google Places API. You can find the latest version on the Google Maven Repository.Click the "Sync Now" button to resolve the dependency.
Implementing the location permissions
Before we can access the user's location, we need to request permission from the user.
- Open the
AndroidManifest.xml
file. - Add the following permissions inside the
<manifest>
tag:<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Retrieving the user's current location
To find nearby businesses and services, we first need to retrieve the user's current location.
- Open the Java/Kotlin file for your main activity.
- Add the following code to the
onCreate
method:LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String locationProvider = LocationManager.NETWORK_PROVIDER; Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); if (lastKnownLocation != null) { double latitude = lastKnownLocation.getLatitude(); double longitude = lastKnownLocation.getLongitude(); // Use latitude and longitude to fetch nearby places }
Fetching nearby places using the Google Places API
Now that we have the user's location, we can use the Google Places API to fetch nearby places.
Add the following code inside the
if (lastKnownLocation != null)
block:Places.initialize(getApplicationContext(), "YOUR_API_KEY"); PlacesClient placesClient = Places.createClient(this); String apiKey = "YOUR_API_KEY"; String type = "restaurant"; // Change this to the desired type of place int radius = 1000; // Change this to the desired radius in meters LatLng userLocation = new LatLng(latitude, longitude); String locationString = userLocation.latitude + "," + userLocation.longitude; // Create a new Places API request FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(Collections.singletonList(type)); request.setLocationBias(RectangularBounds.newInstance(userLocation, userLocation)); request.setFields(Arrays.asList(Place.Field.NAME, Place.Field.ADDRESS, Place.Field.PHONE_NUMBER)); // Fetch nearby places asynchronously placesClient.findCurrentPlace(request).addOnSuccessListener((response) -> { for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) { Place place = placeLikelihood.getPlace(); Log.i("Nearby Place", "Name: " + place.getName()); Log.i("Nearby Place", "Address: " + place.getAddress()); Log.i("Nearby Place", "Phone Number: " + place.getPhoneNumber()); } }).addOnFailureListener((exception) -> { Log.e("Error", "Error getting nearby places: " + exception.getMessage()); });
Replace
"YOUR_API_KEY"
with the API key you obtained from the Google Cloud Console.
Displaying nearby places on the UI
To display the fetched nearby places on the user interface, we can use a RecyclerView or any other UI component of your choice.
Create a layout file for the RecyclerView item,
item_place.xml
, and design it according to your requirements. Include TextViews for name, address, and phone number.Create a new Java/Kotlin class
PlaceAdapter
to act as the adapter for the RecyclerView. Implement the necessary methods, includingonCreateViewHolder
,onBindViewHolder
, andgetItemCount
.Modify your main activity's XML layout file to include a RecyclerView with the desired ID.
In your main activity's Java/Kotlin file, add the following code to initialize the RecyclerView and set up the adapter:
RecyclerView recyclerView = findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setAdapter(new PlaceAdapter(nearbyPlacesList));
Update the
addOnSuccessListener
inside theplacesClient.findCurrentPlace(request)
callback to add the fetched places to thenearbyPlacesList
and notify the adapter of the data change:List<Place> nearbyPlacesList = new ArrayList<>(); // ... placesClient.findCurrentPlace(request).addOnSuccessListener((response) -> { for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) { Place place = placeLikelihood.getPlace(); nearbyPlacesList.add(place); } recyclerView.getAdapter().notifyDataSetChanged(); }).addOnFailureListener((exception) -> { Log.e("Error", "Error getting nearby places: " + exception.getMessage()); });
Now, when the app retrieves nearby places successfully, they will be displayed in the RecyclerView.
Conclusion
Congratulations! You have learned how to use Android's location services and the Google Places API to find nearby businesses and services, and display them in your Android app. You can further enhance the app by implementing search filters, ratings, and other features provided by the Google Places API. Happy coding!