Fotos del lugar

Seleccionar plataforma: Android iOS JavaScript Servicio web

Puedes usar el SDK de Places para Android a fin de solicitar una foto de lugar para mostrar en tu aplicación. Las fotos que muestra el servicio de fotos provienen de diversas fuentes, incluidos propietarios de empresas y fotos que aportan los usuarios. Para recuperar una imagen de un lugar, debes seguir estos pasos:

  1. Obtén un objeto Place (usa fetchPlace() o findCurrentPlace()). Asegúrate de incluir el campo PHOTO_METADATAS en tu solicitud.
  2. En el OnSuccessListener de tu FetchPlaceRequest, agrega un FetchPhotoRequest y, de manera opcional, especifica la altura y el ancho máximos (en píxeles). Las fotos pueden tener un ancho o una altura máximos de 1,600 px.
  3. Agrega un elemento OnSuccessListener y obtén el mapa de bits de FetchPhotoResponse.

Obtener una foto del lugar

El siguiente ejemplo demuestra cómo obtener una foto de un lugar.

Java


// Define a Place ID.
final String placeId = "INSERT_PLACE_ID_HERE";

// Specify fields. Requests for photos must always have the PHOTO_METADATAS field.
final List<Place.Field> fields = Collections.singletonList(Place.Field.PHOTO_METADATAS);

// Get a Place object (this example uses fetchPlace(), but you can also use findCurrentPlace())
final FetchPlaceRequest placeRequest = FetchPlaceRequest.newInstance(placeId, fields);

placesClient.fetchPlace(placeRequest).addOnSuccessListener((response) -> {
    final Place place = response.getPlace();

    // Get the photo metadata.
    final List<PhotoMetadata> metadata = place.getPhotoMetadatas();
    if (metadata == null || metadata.isEmpty()) {
        Log.w(TAG, "No photo metadata.");
        return;
    }
    final PhotoMetadata photoMetadata = metadata.get(0);

    // Get the attribution text.
    final String attributions = photoMetadata.getAttributions();

    // Create a FetchPhotoRequest.
    final FetchPhotoRequest photoRequest = FetchPhotoRequest.builder(photoMetadata)
        .setMaxWidth(500) // Optional.
        .setMaxHeight(300) // Optional.
        .build();
    placesClient.fetchPhoto(photoRequest).addOnSuccessListener((fetchPhotoResponse) -> {
        Bitmap bitmap = fetchPhotoResponse.getBitmap();
        imageView.setImageBitmap(bitmap);
    }).addOnFailureListener((exception) -> {
        if (exception instanceof ApiException) {
            final ApiException apiException = (ApiException) exception;
            Log.e(TAG, "Place not found: " + exception.getMessage());
            final int statusCode = apiException.getStatusCode();
            // TODO: Handle error with given status code.
        }
    });
});

      

Kotlin


// Define a Place ID.
val placeId = "INSERT_PLACE_ID_HERE"

// Specify fields. Requests for photos must always have the PHOTO_METADATAS field.
val fields = listOf(Place.Field.PHOTO_METADATAS)

// Get a Place object (this example uses fetchPlace(), but you can also use findCurrentPlace())
val placeRequest = FetchPlaceRequest.newInstance(placeId, fields)

placesClient.fetchPlace(placeRequest)
    .addOnSuccessListener { response: FetchPlaceResponse ->
        val place = response.place

        // Get the photo metadata.
        val metada = place.photoMetadatas
        if (metada == null || metada.isEmpty()) {
            Log.w(TAG, "No photo metadata.")
            return@addOnSuccessListener
        }
        val photoMetadata = metada.first()

        // Get the attribution text.
        val attributions = photoMetadata?.attributions

        // Create a FetchPhotoRequest.
        val photoRequest = FetchPhotoRequest.builder(photoMetadata)
            .setMaxWidth(500) // Optional.
            .setMaxHeight(300) // Optional.
            .build()
        placesClient.fetchPhoto(photoRequest)
            .addOnSuccessListener { fetchPhotoResponse: FetchPhotoResponse ->
                val bitmap = fetchPhotoResponse.bitmap
                imageView.setImageBitmap(bitmap)
            }.addOnFailureListener { exception: Exception ->
                if (exception is ApiException) {
                    Log.e(TAG, "Place not found: " + exception.message)
                    val statusCode = exception.statusCode
                    TODO("Handle error with given status code.")
                }
            }
    }

      

Atribuciones

En la mayoría de los casos, las fotos de lugares se pueden usar sin atribución o tendrán la atribución requerida incluida como parte de la imagen. Sin embargo, si la instancia de PhotoMetadata que se muestra incluye una atribución, debes incluir la atribución adicional en tu aplicación en cualquier lugar en el que muestres la imagen. Para obtener más información, consulta Cómo mostrar atribuciones.

Uso y facturación

Se cobra un SKU Places Photo por las llamadas a fetchPhoto(). Consulta la página Uso y facturación para obtener más detalles.