Visualiza imágenes y anotaciones

Desarrolladores del Espacio Económico Europeo (EEE)

El extremo SearchDestinations de la API de Geocoding proporciona contexto hiperlocal, incluidos los puntos de navegación y las entradas. Para mejorar la experiencia del usuario, la respuesta puede incluir parámetros para la API de Street View Static, lo que te permite mostrar imágenes relevantes para estas ubicaciones.

Solicita imágenes y anotaciones

Para recibir información sobre las imágenes y las anotaciones, debes incluir los siguientes campos en el encabezado X-Goog-FieldMask:

Solicitud cURL de ejemplo

curl -X POST -d '{
  "place": "places/ChIJkU89GL9ZwokRvVjWDQzhaNg"
}' \
-H 'Content-Type: application/json' \
-H "X-Goog-Api-Key: API_KEY" \
-H "X-Goog-FieldMask: destinations.navigationPoints.streetViewThumbnail,destinations.navigationPoints.entranceAnnotation,destinations.entrances.streetViewThumbnail,destinations.entrances.streetViewAnnotation" \
https://geocode.googleapis.com/v4alpha/geocode/destinations

Ejemplo de respuesta JSON

{
  "destinations": [
    {
      "entrances": [
        {
          "location": {
            "latitude": 40.7406763,
            "longitude": -74.0020733
          },
          "tags": [
            "PREFERRED"
          ],
          "place": "places/ChIJkU89GL9ZwokRvVjWDQzhaNg",
          "streetViewThumbnail": {
            "pano": "EUKaIR67fBVmpsHnXuIevA",
            "widthPx": 400,
            "heightPx": 600,
            "headingDegree": 331.06186,
            "fovDegree": 60
          },
          "streetViewAnnotation": {
            "coordinates": [
              {
                "xPx": 184.7,
                "yPx": 290.4
              },
              {
                "xPx": 213.3,
                "yPx": 289.4
              },
              {
                "xPx": 214.8,
                "yPx": 330.8
              },
              {
                "xPx": 186.0,
                "yPx": 332.5
              }
            ]
          }
        }
      ]
    }
  ]
}

Los objetos Entrance y NavigationPoint de la respuesta pueden contener un campo streetViewThumbnail con los siguientes campos:

Campo Descripción Parámetro de API estático
pano Es el ID de una panorámica específica. pano
widthPx Ancho sugerido para la imagen. size (parte del ancho)
heightPx Altura sugerida para la imagen. size (parte de la altura)
headingDegree Orientación de la cámara según la brújula (de 0 a 360). heading
pitchDegree Ángulo vertical de la cámara (de -90 a 90). pitch
fovDegree Campo visual horizontal (0 a 120). fov

Solicita una imagen

Para solicitar una imagen de Street View, usa los valores del objeto streetViewThumbnail para construir una URL para la API de Street View Static.

URL de ejemplo

A continuación, se muestra un ejemplo de una URL de la API de Street View Static construida:

https://maps.googleapis.com/maps/api/streetview?size=400x600&pano=EUKaIR67fBVmpsHnXuIevA&heading=331.06186&fov=60&key=API_KEY&signature=YOUR_SIGNATURE

Código de muestra: TypeScript

La siguiente función de TypeScript muestra cómo construir la URL de la API de Static Street View a partir del resultado del extremo de Destinations.

interface StreetViewThumbnail {
  pano: string;
  widthPx: number;
  heightPx: number;
  headingDegree: number;
  pitchDegree: number;
  fovDegree: number;
}

function getStreetViewUrl(thumbnail: StreetViewThumbnail, apiKey: string): string {
  const params = new URLSearchParams({
    size: `${thumbnail.widthPx}x${thumbnail.heightPx}`,
    pano: thumbnail.pano,
    heading: thumbnail.headingDegree.toString(),
    pitch: thumbnail.pitchDegree.toString(),
    fov: thumbnail.fovDegree.toString(),
    key: apiKey,
  });

  return `https://maps.googleapis.com/maps/api/streetview?${params.toString()}`;
}

Anotaciones de imágenes

Si se devuelve un Entrance o un NavigationPoint, también se puede incluir una anotación de imagen de la entrada correspondiente en el campo streetViewAnnotation o entranceAnnotation. Proporciona las coordenadas de píxeles de un polígono que describe la entrada dentro de la imagen en miniatura.

Estas anotaciones están diseñadas para la renderización del cliente. Puedes usarlos para dibujar una superposición (por ejemplo, con SVG o un <canvas>) sobre la imagen que devuelve la API de Static.

Sistema de coordenadas de anotación

El origen (0,0) es la esquina superior izquierda de la imagen.

  • xPx: Distancia horizontal desde el borde izquierdo.
  • yPx: Distancia vertical desde el borde superior.

Para asegurarte de que el polígono se alinee correctamente, debes solicitar la imagen a la API de Static con el size especificado por widthPx y heightPx.

Código de muestra: Dibujo de anotaciones (TypeScript y SVG)

En este ejemplo, se muestra cómo usar TypeScript y SVG para superponer el polígono de anotación de entrada en la imagen de Street View.

TypeScript

interface Coordinate {
  xPx: number;
  yPx: number;
}

interface StreetViewAnnotation {
  coordinates: Coordinate[];
}

function drawAnnotations(annotation: StreetViewAnnotation, width: number, height: number) {
  const svg = document.getElementById('annotation-overlay') as unknown as SVGSVGElement;
  const polygon = document.getElementById('entrance-polygon') as unknown as SVGPolygonElement;

  // Set SVG dimensions to match the image
  svg.setAttribute('width', width.toString());
  svg.setAttribute('height', height.toString());
  svg.setAttribute('viewBox', `0 0 ${width} ${height}`);

  // Construct points string for the polygon
  const points = annotation.coordinates
    .map(coord => `${coord.xPx},${coord.yPx}`)
    .join(' ');

  polygon.setAttribute('points', points);
}

// Example usage:
const annotation = {
  coordinates: [
    {xPx: 184.7, yPx: 290.4},
    {xPx: 213.3, yPx: 289.4},
    {xPx: 214.8, yPx: 330.8},
    {xPx: 186.0, yPx: 332.5}
  ]
};
drawAnnotations(annotation, 400, 600);

HTML

<div style="position: relative; display: inline-block;">
  <!-- The Street View image from the previous step -->
  <img id="street-view-image" src="STREET_VIEW_IMAGE" alt="Street View" style="display: block;">

  <!-- SVG overlay for annotations -->
  <svg id="annotation-overlay" style="position: absolute; top: 0; left: 0; pointer-events: none;">
    <polygon id="entrance-polygon" points="" style="fill:rgba(0, 255, 17, 0.3);stroke:rgba(0, 255, 17, 0.9);stroke-width:3" />
  </svg>
</div>

Deberías ver un resultado similar a este:

Google Street View de Nueva York

Comentarios

Esta es una función experimental de la API de Geocoding. Agradeceríamos tus comentarios en geocoding-feedback-channel@google.com.