The Android Google Places API is a powerful tool that allows developers to harness the power of Google’s extensive database of geographic places. This API provides access to detailed information about millions of places around the world, including restaurants, hotels, landmarks, and more. In this article, we’ll explore the key features of the Android Google Places API, learn how to set it up in your project, and discuss some potential use cases.
The Android Google Places API offers a variety of features, including:
To use the Android Google Places API, you’ll first need to enable it for your project in the Google Cloud Console and obtain an API key. Follow these steps to get started:
Next, add the following dependencies to your project’s build.gradle
file:
dependencies {
implementation 'com.google.android.gms:play-services-places:17.0.0'
}
Finally, add your API key to your project’s AndroidManifest.xml
file:
<manifest>
<!-- ... -->
<application>
<!-- ... -->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY" />
</application>
</manifest>
Replace YOUR_API_KEY
with the API key you obtained from the Google Cloud Console.
Now that you’ve set up the Android Google Places API, you can start using it in your application. Here are some examples of how to use the API’s key features:
To search for places near a specific location, use the PlacesClient.findPlaceFromText()
method. This method returns a list of places that match the search query:
// Create a PlacesClient instance
Places.initialize(context, "YOUR_API_KEY");
PlacesClient placesClient = Places.createClient(context);
// Define the search parameters
String query = "restaurants";
LatLng location = new LatLng(37.4219999,-122.0840575);
int radius = 1000;
// Build the request
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setQuery(query)
.setLocationBias(RectangularBounds.newInstance(
LatLngBounds.builder()
.include(SphericalUtil.computeOffset(location, radius, 0))
.include(SphericalUtil.computeOffset(location, radius, 180))
.build()))
.build();
// Execute the request
placesClient.findAutocompletePredictions(request).addOnSuccessListener(response -> {
// Handle the search results
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
}).addOnFailureListener(exception -> {
// Handle the error
Log.e(TAG, "Error getting search results", exception);
});
To retrieve detailed information about a place, use the PlacesClient.fetchPlace()
method. This method requires a Place ID, which you can obtain from a search result:
// Define the place ID and fields to fetch
String placeId = "ChIJN1t_tDeuEmsRUsoyG83frY4";
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.PHONE_NUMBER);
// Build the request
FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);
// Execute the request
placesClient.fetchPlace(request).addOnSuccessListener(response -> {
// Handle the place details
Place place = response.getPlace();
Log.i(TAG, "Place found: " + place.getName());
Log.i(TAG, "Address: " + place.getAddress());
}).addOnFailureListener(exception-> {
// Handle the error
Log.e(TAG, "Error fetching place details", exception);
});
To provide autocomplete suggestions for place searches, use the PlacesClient.findAutocompletePredictions()
method:
// Define the search query
String query = "san franc";
// Build the request
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
.setQuery(query)
.build();
// Execute the request
placesClient.findAutocompletePredictions(request).addOnSuccessListener(response -> {
// Handle the autocomplete suggestions
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
Log.i(TAG, prediction.getFullText(null).toString());
}
}).addOnFailureListener(exception -> {
// Handle the error
Log.e(TAG, "Error getting autocomplete predictions", exception);
});
To access photos associated with a place, use the PlacesClient.fetchPhoto()
method. This method requires a PhotoMetadata object, which you can obtain from a place’s details:
// Define the place ID and fields to fetch
String placeId = "ChIJN1t_tDeuEmsRUsoyG83frY4";
List<Place.Field> placeFields = Arrays.asList(Place.Field.PHOTO_METADATAS);
// Build the request
FetchPlaceRequest request = FetchPlaceRequest.newInstance(placeId, placeFields);
// Execute the request
placesClient.fetchPlace(request).addOnSuccessListener(response -> {
// Get the PhotoMetadata object
Place place = response.getPlace();
List<PhotoMetadata> photoMetadataList = place.getPhotoMetadatas();
// Check if the place has photos
if (photoMetadataList != null && !photoMetadataList.isEmpty()) {
PhotoMetadata photoMetadata = photoMetadataList.get(0);
// Build the photo request
FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
.setMaxWidth(500) // Optional: specify the maximum width of the image
.setMaxHeight(500) // Optional: specify the maximum height of the image
.build();
// Execute the photo request
placesClient.fetchPhoto(photoRequest).addOnSuccessListener(fetchPhotoResponse -> {
// Handle the photo
Bitmap bitmap = fetchPhotoResponse.getBitmap();
ImageView imageView = findViewById(R.id.place_image_view);
imageView.setImageBitmap(bitmap);
}).addOnFailureListener(exception -> {
// Handle the error
Log.e(TAG, "Error fetching photo", exception);
});
}
}).addOnFailureListener(exception -> {
// Handle the error
Log.e(TAG, "Error fetching place details", exception);
});
The Android Google Places API is a powerful tool for integrating rich place data into your applications. With its extensive database of places and variety of features, you can create engaging and interactive experiences for your users. From searching for nearby attractions to providing autocomplete suggestions, there are countless ways to leverage the Android Google Places API in your projects.