Connessione a terra con Google Maps in Vertex AI

Il grounding con Google Maps in Vertex AI combina la potenza di Gemini con Google Maps, che ha accesso a informazioni su oltre 250 milioni di luoghi. Questa importante integrazione disponibile tramite Vertex AI è progettata per aiutarti a creare una nuova generazione di applicazioni generative.

Questa pagina spiega come utilizzare Google Maps per basare le risposte del modello LLM.

Panoramica

Grounding con Google Maps in Vertex AI è un servizio che ti consente di utilizzare i dati di Google Maps con i modelli LLM per fornire risposte più accurate e sensibili al contesto ai tuoi prompt. Il grounding con Google Maps è integrato con Vertex AI per supportare l'utilizzo dei dati geografici con il modello Gemini.

La funzionalità di grounding con Google Maps ti aiuta a scoprire nuovi luoghi, pianificare eventi e ricevere consigli su una serie di località. Puoi:

  • Chiedi a un assistente conversazionale informazioni sulla zona e sui luoghi nelle vicinanze. L'assistente ha accesso alle informazioni sul tempo di percorrenza e può comunicarti la distanza di un luogo dalla tua posizione. Ad esempio, Ci sono parchi nelle vicinanze?
  • Visualizza descrizioni personalizzate del luogo che corrispondono ai tuoi criteri. Ad esempio, puoi dirmi di più sui parchi e sui ristoranti adatti alle famiglie che si trovano a pochi passi di distanza?

Il grounding con Google Maps ti consente di creare applicazioni di AI generativa da una chat basata su LLM utilizzando il contesto geospaziale per generare un riepilogo personalizzato basato sulla posizione per aiutarti a prendere decisioni migliori.

Per ricevere assistenza, invia un messaggio a maps-grounding-feedback-external@google.com.

Modelli supportati

Questa sezione elenca i modelli che supportano la fondazione con Google Maps.

Per saperne di più sui modelli Gemini, consulta Modelli Gemini.

Accesso a Grounding con Google Maps

Per utilizzare Grounding con Google Maps in Vertex AI:

  1. Per richiedere l'accesso per utilizzare Grounding con Google Maps in Vertex AI per progetti specifici, compila e invia il modulo di attivazione o disattivazione dell'utilizzo di Google Maps.

    Questo modulo richiede il tuo indirizzo email, il nome della società, l'ID progetto e la tua accettazione dei termini.

  2. Se non hai un progetto, consulta Creazione e gestione dei progetti.

  3. Nella console Google Cloud , vai alla pagina API Maps Grounding.

    Vai all'API Maps Grounding

    Per abilitare l'API Maps Grounding, fai clic su Abilita. Seleziona un progetto e viene visualizzata la pagina API Maps Grounding.

  4. Nella console Google Cloud , vai alla pagina API Maps JavaScript.

    Vai all'API Maps JavaScript

    Per attivare JavaScript, fai clic su Attiva. Seleziona un progetto e viene visualizzata la pagina API e Servizi.

  5. Per verificare che Google Maps sia abilitato, vai a Vertex AI Studio.

    Vai a Vertex AI Studio

    1. Seleziona il progetto per cui hai abilitato le API.

    2. Per attivare la funzionalità di Google Maps nella sezione Strumenti del riquadro del modello, fai clic sul pulsante di attivazione/disattivazione Grounding: Google.

    3. Seleziona Anteprima di Google Maps.

    4. Inserisci la chiave API.

      1. Se non disponi di una chiave API, consulta la sezione Creazione di chiavi API.
      2. Limita l'utilizzo delle API limitando le chiavi API.
    5. Seleziona la località per una risposta basata sulla posizione.

    6. Fai clic su Applica.

Proprietà del luogo

Questa sezione elenca le proprietà dei luoghi utilizzate per descrivere le località e utilizzate da Grounding con Google Maps per generare risposte. Queste proprietà vengono utilizzate per determinare i tipi di domande a cui può rispondere Grounding con Google Maps.

Proprietà del luogo di esempio

Questo elenco fornisce un campionamento in ordine alfabetico delle proprietà dei luoghi che potrebbero essere utilizzate dal modello per generare risposte.

  • Indirizzo
  • Solo contanti
  • Carta di credito
  • Ritiro all'esterno
  • Carta di debito
  • Distanza
  • Parcheggio gratuito
  • Musica dal vivo
  • Menu per bambini
  • Orari di apertura
  • Animali ammessi
  • Serve birra
  • Serve cibo vegetariano
  • Accessibile in sedia a rotelle
  • Wi-Fi

Esempi di utilizzo delle proprietà dei luoghi

Gli esempi seguenti utilizzano le proprietà dei luoghi nelle domande su diversi tipi di luoghi. La generazione controllata con Google Maps utilizza le proprietà per comprendere la tua intenzione e poi fornisce risposte pertinenti in base ai dati associati ai luoghi in Google Maps.

  • Organizzare una cena in famiglia: potresti chiedere: "Il ristorante "The Italian Place" è adatto ai bambini e offre il servizio d'asporto?" Qual è la loro valutazione?

    Le risposte a queste domande ti aiutano a determinare se un ristorante è adatto a una famiglia e se offre un servizio conveniente.

  • Controllare l'accessibilità per un amico: potresti chiedere: "Ho bisogno di un ristorante con un ingresso accessibile in sedia a rotelle".

    Una risposta a questa richiesta potrebbe aiutarti a determinare se la posizione soddisfa esigenze di accessibilità specifiche.

  • Trovare un posto per uno spuntino a tarda notte: potresti chiedere, "Burger Joint" è aperto ora? Serve la cena? Quali sono gli orari di apertura per venerdì?

    Le risposte a queste domande ti aiutano a trovare un'attività aperta che serve un pasto specifico in un determinato momento.

  • Incontrare un cliente per un caffè: potresti chiedere: Il "Cafe Central" ha il Wi-Fi? Servono caffè? Qual è il loro livello di prezzo e accettano carte di credito?

    Le risposte a queste domande ti aiutano a valutare l'idoneità di un caffè per un incontro di lavoro in base a servizi, offerte e opzioni di pagamento.

Utilizzare Grounding con Google Maps per basare il modello

Puoi utilizzare l'API Google Maps per basare le risposte del modello su dati reali.

Questi esempi di codice mostrano come utilizzare l'API Maps per basare le risposte del modello utilizzando Grounding con Google Maps.

Python

Installa

pip install --upgrade google-genai

Per saperne di più, consulta la documentazione di riferimento dell'SDK.

Imposta le variabili di ambiente per utilizzare l'SDK Gen AI con Vertex AI:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai
from google.genai.types import (
    ApiKeyConfig,
    AuthConfig,
    GenerateContentConfig,
    GoogleMaps,
    HttpOptions,
    Tool,
)

# TODO(developer): Update below line with your Google Maps API key
GOOGLE_MAPS_API_KEY = "YOUR_GOOGLE_MAPS_API_KEY"

client = genai.Client(http_options=HttpOptions(api_version="v1"))

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="Recommend a good restaurant in San Francisco.",
    config=GenerateContentConfig(
        tools=[
            # Use Google Maps Tool
            Tool(
                google_maps=GoogleMaps(
                    auth_config=AuthConfig(
                        api_key_config=ApiKeyConfig(
                            api_key_string=GOOGLE_MAPS_API_KEY,
                        )
                    )
                )
            )
        ],
    ),
)

print(response.text)
# Example response:
# 'San Francisco boasts a vibrant culinary scene...'

REST

Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:

  • LOCATION: La regione in cui elaborare la richiesta.
  • PROJECT_ID: il tuo ID progetto
  • MODEL_ID: l'ID modello del modello multimodale.
  • TEXT: Le istruzioni di testo da includere nel prompt.
  • API_KEY: la tua chiave API.
  • LATITUDE: la latitudine della posizione.
  • LONGITUDE: la longitudine della posizione.

Metodo HTTP e URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

Corpo JSON della richiesta:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "googleMaps": {
      "authConfig": {
        "apiKeyConfig": {
          "apiKeyString": "API_KEY"
        }
      }
    }
  }],
  "toolConfig": {
    "retrievalConfig": {
      "latLng": {
        "latitude": LATITUDE,
        "longitude": LONGITUDE
      }
    }
  },
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID"
}

Per inviare la richiesta, espandi una di queste opzioni:

Dovresti ricevere una risposta JSON simile alla seguente:

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here are a few options for late-night burgers in San Jose, based on the search results. Keep in mind that \"late night\" can be subjective, so I've included places with varying closing times. I recommend double-checking their hours before you go, as these can change.\n\n*   **Campus Burgers:** Open until 12:00 AM every night except Sunday (closed).\n*   **Lazy Dog Restaurant & Bar:** Open until 12:00 AM every night.\n*   **Dough Burger:** Open until 1:30 AM Monday through Thursday and Sunday, and until 3:00 AM on Friday and Saturday.\n*   **El Apartamento Colombian Burgers:** Open until 1:00 AM on Friday and Saturday, and until 10:30 PM Monday through Wednesday and until 11:00 PM Thursday and Sunday.\n*   **Paper Plane:** Open until 2:00 AM Thursday through Saturday, and until 12:00 AM on Tuesday and Wednesday and Sunday. Closed on Monday.\n\nNote that opening hours are subject to change.\n"
          }
        ]
      },
      "finishReason": "STOP",
      "groundingMetadata": {
        "retrievalQueries": [
          "late night burger san jose"
        ],
        "groundingChunks": [
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=15700677770979677665",
              "title": "El Apartamento Colombian Burgers",
              "text": "**About:**\n\n* **Type:** Hamburger Restaurant\n* **Address:** 76 E Santa Clara St, San Jose, CA 95113, USA\n* **Open Now:** No\n* **Rating:** 4.9 (25 reviews)\n* **Offers Takeout:** Yes\n* **Offers Delivery:** Yes\n* **Offers Dine-in:** Yes\n* **Good for Children:** Yes\n* **Outdoor Seating:** No\n* **Live Music:** No\n* **Curbside Pickup:** Yes\n\n**Opening Hours (local time):**\n\n* Monday: 5:00 – 10:30 PM\n* Tuesday: 5:00 – 10:30 PM\n* Wednesday: 5:00 – 10:30 PM\n* Thursday: 4:00 – 11:00 PM\n* Friday: 4:00 PM – 1:00 AM\n* Saturday: 4:00 PM – 1:00 AM\n* Sunday: 4:00 – 11:00 PM\n\n**Parking options:**\n\n* **Free street parking:** Yes\n\n**Accessibility:**\n\n* **Wheelchair accessible parking:** Yes\n* **Wheelchair accessible entrance:** Yes\n\n**Payment options:**\n\n* **Credit Card:** Yes\n* **Cash Only:** No\n\n**Distance & Travel Time:**\n\n* 4733.0 kilometers\n* 43.4 hours"
            }
          },
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=8798666889278262772",
              "title": "Campus Burgers",
              "text": "**About:**\n\n* **Type:** Hamburger Restaurant\n* **Address:** 108 Paseo de San Antonio, San Jose, CA 95113, USA\n* **Open Now:** Yes\n* **Rating:** 4.4 (207 reviews)\n* **Price Level:** Inexpensive\n* **Phone:** (408) 352-5507\n* **Additional Summary:** Simple hamburger restaurant with a limited menu of comfort fare such as burgers and fries.\n* **Offers Takeout:** Yes\n* **Offers Delivery:** Yes\n* **Offers Dine-in:** Yes\n* **Good for Children:** Yes\n* **Good for Groups:** Yes\n* **Outdoor Seating:** Yes\n* **Live Music:** No\n* **Menu for Children:** No\n* **Serves Cocktails:** No\n* **Serves Dessert:** Yes\n* **Serves Coffee:** No\n* **Good for Watching Sports:** No\n* **Serves Lunch:** Yes\n* **Serves Dinner:** Yes\n\n**Opening Hours (local time):**\n\n* Monday: 11:00 AM – 12:00 AM\n* Tuesday: 11:00 AM – 12:00 AM\n* Wednesday: 11:00 AM – 12:00 AM\n* Thursday: 11:00 AM – 12:00 AM\n* Friday: 11:00 AM – 12:00 AM\n* Saturday: 11:00 AM – 12:00 AM\n* Sunday: Closed\n\n**Parking options:**\n\n* **Paid parking lot:** Yes\n* **Free street parking:** Yes\n* **Paid street parking:** Yes\n* **Valet parking:** No\n* **Paid garage parking:** Yes\n\n**Accessibility:**\n\n* **Wheelchair accessible parking:** Yes\n* **Wheelchair accessible entrance:** Yes\n\n**Payment options:**\n\n* **Credit Card:** Yes\n* **Debit Card:** Yes\n* **Cash Only:** No\n* **NFC:** Yes\n\n**Distance & Travel Time:**\n\n* 4732.5 kilometers\n* 43.4 hours"
            }
          },
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=3915125089239094417",
              "title": "Paper Plane",
              "text": "**About:**\n\n* **Type:** Bar\n* **Address:** 72 S 1st St, San Jose, CA 95113, USA\n* **Open Now:** No\n* **Rating:** 4.4 (2452 reviews)\n* **Price Level:** Moderate\n* **Phone:** (408) 713-2625\n* **Summary:** Relaxed spot with a long bar in an exposed brick space for creative or classic cocktails & snacks.\n* **Additional Summary:** Casual, popular bar serving signature cocktails and New American fare, including burgers and tacos.\n* **Takes Reservations:** Yes\n* **Offers Takeout:** Yes\n* **Offers Dine-in:** Yes\n* **Good for Children:** No\n* **Allows Dogs:** No\n* **Has Restroom:** Yes\n* **Good for Groups:** Yes\n* **Outdoor Seating:** No\n* **Live Music:** No\n* **Serves Cocktails:** Yes\n* **Good for Watching Sports:** No\n* **Serves Beer:** Yes\n* **Serves Wine:** Yes\n\n**Opening Hours (local time):**\n\n* Monday: Closed\n* Tuesday: 5:00 PM – 12:00 AM\n* Wednesday: 5:00 PM – 12:00 AM\n* Thursday: 5:00 PM – 2:00 AM\n* Friday: 5:00 PM – 2:00 AM\n* Saturday: 5:00 PM – 2:00 AM\n* Sunday: 5:00 PM – 12:00 AM\n\n**Parking options:**\n\n* **Paid parking lot:** Yes\n* **Free street parking:** Yes\n* **Paid street parking:** Yes\n* **Valet parking:** No\n* **Paid garage parking:** Yes\n\n**Accessibility:**\n\n* **Wheelchair accessible entrance:** Yes\n* **Wheelchair accessible restroom:** Yes\n* **Wheelchair accessible seating:** Yes\n\n**Payment options:**\n\n* **Credit Card:** Yes\n* **Cash Only:** No\n* **NFC:** Yes\n\n**Distance & Travel Time:**\n\n* 4733.0 kilometers\n* 43.4 hours"
            }
          },
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=12662287798905863411",
              "title": "Lazy Dog Restaurant & Bar",
              "text": "**About:**\n\n* **Type:** American Restaurant\n* **Address:** 5305 Almaden Expy, San Jose, CA 95118, USA\n* **Open Now:** Yes\n* **Rating:** 4.2 (940 reviews)\n* **Price Level:** Moderate\n* **Phone:** (408) 786-9594\n* **Summary:** Relaxed, lodge-chic chain serving global comfort fare, including stir-fries, pot roast & pastas.\n* **Additional Summary:** American food including comfort fare and small plates served in a casual setting with a bar.\n* **Takes Reservations:** Yes\n* **Offers Takeout:** Yes\n* **Offers Delivery:** Yes\n* **Offers Dine-in:** Yes\n* **Good for Children:** Yes\n* **Allows Dogs:** Yes\n* **Has Restroom:** Yes\n* **Good for Groups:** Yes\n* **Outdoor Seating:** Yes\n* **Live Music:** No\n* **Menu for Children:** Yes\n* **Serves Cocktails:** Yes\n* **Serves Dessert:** Yes\n* **Serves Coffee:** Yes\n* **Has Wifi:** Yes\n* **Good for Watching Sports:** Yes\n* **Curbside Pickup:** Yes\n* **Serves Lunch:** Yes\n* **Serves Dinner:** Yes\n* **Serves Beer:** Yes\n* **Serves Wine:** Yes\n* **Serves Brunch:** Yes\n\n**Opening Hours (local time):**\n\n* Monday: 11:00 AM – 12:00 AM\n* Tuesday: 11:00 AM – 12:00 AM\n* Wednesday: 11:00 AM – 12:00 AM\n* Thursday: 11:00 AM – 12:00 AM\n* Friday: 11:00 AM – 12:00 AM\n* Saturday: 10:00 AM – 12:00 AM\n* Sunday: 10:00 AM – 12:00 AM\n\n**Parking options:**\n\n* **Free parking lot:** Yes\n* **Free street parking:** Yes\n* **Valet parking:** No\n\n**Accessibility:**\n\n* **Wheelchair accessible parking:** Yes\n* **Wheelchair accessible entrance:** Yes\n* **Wheelchair accessible restroom:** Yes\n* **Wheelchair accessible seating:** Yes\n\n**Payment options:**\n\n* **Credit Card:** Yes\n* **Debit Card:** Yes\n* **Cash Only:** No\n* **NFC:** Yes\n\n**Distance & Travel Time:**\n\n* 4745.7 kilometers\n* 43.5 hours"
            }
          },
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=12520445715080978741",
              "title": "Dough Burger",
              "text": "**About:**\n\n* **Type:** Restaurant\n* **Address:** 1721 Old Bayshore Hwy, San Jose, CA 95112, USA\n* **Open Now:** No\n* **Rating:** 4.2 (61 reviews)\n* **Phone:** (408) 515-0161\n* **Offers Takeout:** Yes\n* **Offers Delivery:** Yes\n* **Offers Dine-in:** Yes\n* **Good for Children:** Yes\n* **Live Music:** No\n* **Curbside Pickup:** Yes\n* **Serves Lunch:** Yes\n* **Serves Dinner:** Yes\n\n**Opening Hours (local time):**\n\n* Monday: 6:00 PM – 1:30 AM\n* Tuesday: 6:00 PM – 1:30 AM\n* Wednesday: 6:00 PM – 1:30 AM\n* Thursday: 6:00 PM – 1:30 AM\n* Friday: 6:00 PM – 3:00 AM\n* Saturday: 6:00 PM – 3:00 AM\n* Sunday: 6:00 PM – 1:30 AM\n\n**Parking options:**\n\n* **Free parking lot:** Yes\n* **Free street parking:** Yes\n\n**Accessibility:**\n\n* **Wheelchair accessible parking:** Yes\n* **Wheelchair accessible entrance:** Yes\n\n**Payment options:**\n\n* **Credit Card:** Yes\n* **Cash Only:** No\n\n**Distance & Travel Time:**\n\n* 4740.1 kilometers\n* 43.3 hours"
            }
          }
        ],
        "groundingSupports": [
          {
            "segment": {
              "startIndex": 267,
              "endIndex": 346,
              "text": "*   **Campus Burgers:** Open until 12:00 AM every night except Sunday (closed)."
            },
            "groundingChunkIndices": [
              1
            ],
            "confidenceScores": [
              0.76444983
            ]
          }
        ],
        "googleMapsWidgetContextToken": "widgetcontent/AcBXPQfo6pGrCXPJeN2xtADMw1TPz8Wzwm-..."
      }
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 7,
    "candidatesTokenCount": 236,
    "totalTokenCount": 243,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 7
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 236
      }
    ]
  },
  "modelVersion": "gemini-2.0-flash-001",
  "createTime": "2025-04-03T20:11:51.118341Z"
}
```

Esegui il rendering del widget contestuale di Google Maps

Il rendering del widget contestuale di Google Maps è obbligatorio nell'ambito dell'utilizzo di Grounding con Google Maps in Vertex AI. In qualsiasi risposta basata su Google Maps, è presente un googleMapsWidgetContextToken corrispondente che viene utilizzato per il rendering del widget contestuale in prossimità della risposta generata.

  "googleMapsWidgetContextToken": "widgetcontent/AcBXPQdpWQWbap9H-OH8sEKmOXxmEKAYvff0tvthhneMQC3VrqWCjpnPBl4-Id98FGiA_S_t8aeAeJj0T6JkWFX56Bil8oBSR0W8JH3C_RSYLbTjxKdpxc9yNn6JcZTtolIRZon9xi6WpNGuSyjcIxWu2S0hwpasNOpUlWrG1RxVCB4WD1fsz_pwR236mG36lMxevXTQ_JnfdYNuQwQ4Lc3vn...<snip>...
  Ts5VJE_b3IC5eE_6wez0nh61r7foTUZpP7BXMwxR-7Wyfcj6x1v6mIWsFGr1o0p_HSAMNqWPg-aFVnkPLhAkOR6MaNZOfezTva-gxHlu7z_haFvYxcUE1qfNVQ",

La pagina che mostra il widget deve utilizzare la versione alfa dell'API Google Maps JavaScript. Per ulteriori informazioni, consulta Caricare l'API Maps JavaScript.

Per caricare l'API Google Maps JS, devi utilizzare la chiave API abilitata per Grounding con Google Maps in Vertex AI.

Questo esempio di codice mostra come creare un widget utilizzando HTML.

  <body>
    <gmp-place-contextual id="widget"></gmp-place-contextual>
  </body>

Nel tuo JavaScript, utilizza il seguente metodo per aggiornare il token di contesto:

function updateWidget(contextToken) {
  let widget = document.querySelector('#widget');
  widget.contextToken = contextToken;
}

Puoi anche creare un widget in modo dinamico con il seguente codice:

async function createWidget(contextToken) {
  await google.maps.importLibrary('places');
  let widgetContainer = document.querySelector('#wc');  // a div that contains the widget
  const placeContextualElement = new
      google.maps.places.PlaceContextualElement({ contextToken });
  widgetContainer.appendChild(placeContextualElement);
}

Questo esempio di codice HTML mostra come utilizzare le opzioni di configurazione per alternare due layout diversi (compact o vertical).

    <gmp-place-contextual id="widget">
      <gmp-place-contextual-list-config layout="compact">
      </gmp-place-contextual-list-config>
    </gmp-place-contextual>

Questo esempio di codice HTML mostra come disattivare la mappa.

    <gmp-place-contextual id="widget">
      <gmp-place-contextual-list-config map-hidden>
      </gmp-place-contextual-list-config>
    </gmp-place-contextual>

Questo esempio di codice JavaScript mostra come specificare un layout compact e come nascondere la mappa.

  const widgetConfig = new google.maps.places.PlaceContextualListConfigElement({
    layout: 'compact',
    mapHidden: true
  });
  widget.appendChild(widgetConfig);

Passaggi successivi

  • Per saperne di più su come basare i modelli Gemini sui tuoi dati, vedi Grounding con i tuoi dati.
  • Per scoprire di più sulle best practice per l'AI responsabile e sui filtri di sicurezza di Vertex AI, consulta AI responsabile.