Published on

Finding Nearby Businesses and Services on Android

Authors
  • avatar
    Name
    how-to.digital
    Twitter

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

  1. Open Android Studio and create a new project.
  2. Choose an appropriate name for your project and select the minimum SDK version that matches your target audience.
  3. Click "Next" and choose "Empty Activity" as the template.
  4. 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.

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one from the dropdown menu at the top.
  3. Click on the "Enable APIs and Services" button.
  4. In the search bar, type "Places API" and select it from the results.
  5. Click the "Enable" button for the Places API.
  6. Go back to the Dashboard and click on the "Credentials" tab.
  7. Click on the "Create Credentials" button and select "API key" from the dropdown menu.
  8. 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.

  1. Open your project's build.gradle file.

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

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

  1. Open the AndroidManifest.xml file.
  2. 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.

  1. Open the Java/Kotlin file for your main activity.
  2. 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.

  1. 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());
    });
    
  2. 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.

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

  2. Create a new Java/Kotlin class PlaceAdapter to act as the adapter for the RecyclerView. Implement the necessary methods, including onCreateViewHolder, onBindViewHolder, and getItemCount.

  3. Modify your main activity's XML layout file to include a RecyclerView with the desired ID.

  4. 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));
    
  5. Update the addOnSuccessListener inside the placesClient.findCurrentPlace(request) callback to add the fetched places to the nearbyPlacesList 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!