SPB Git

Repository Public

maps-grounding.md 26.8 KB 727 lines markdown

1Grounding with Google Maps connects the generative capabilities of Gemini with2the rich, factual, and up-to-date data of Google Maps. This feature enables3developers to easily incorporate location-aware functionality into their4applications. When a user query has a context related to Maps data, the Gemini5model leverages Google Maps to provide factually accurate and fresh answers that6are relevant to the user's specified location or general area.78- **Accurate, location-aware responses:** Leverage Google Maps' extensive and current data for geographically specific queries.9- **Enhanced personalization:** Tailor recommendations and information based on user-provided locations.1011## Get started1213This example demonstrates how to integrate Grounding with Google Maps into your14application to provide accurate, location-aware responses to user queries. The15prompt asks for local recommendations with an optional user location, enabling16the Gemini model to use Google Maps data.1718### Python1920    from google import genai21    from google.genai import types2223    client = genai.Client()2425    prompt = "What are the best Italian restaurants within a 15-minute walk from here?"2627    response = client.models.generate_content(28        model='gemini-3.8-flash',29        contents=prompt,30        config=types.GenerateContentConfig(31            # Turn on grounding with Google Maps32            tools=[types.Tool(google_maps=types.GoogleMaps())],33            # Optionally provide the relevant location context (this is in Los Angeles)34            tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig(35                lat_lng=types.LatLng(36                    latitude=34.050481, longitude=-118.248526))),37        ),38    )3940    print("Generated Response:")41    print(response.text)4243    if grounding := response.candidates[0].grounding_metadata:44      if grounding.grounding_chunks:45        print('-' * 40)46        print("Sources:")47        for chunk in grounding.grounding_chunks:48          print(f'- [{chunk.maps.title}]({chunk.maps.uri})')4950### JavaScript5152    import { GoogleGenAI } from "@google/genai";5354    const ai = new GoogleGenAI({});5556    async function generateContentWithMapsGrounding() {57      const response = await ai.models.generateContent({58        model: "gemini-3.8-flash",59        contents: "What are the best Italian restaurants within a 15-minute walk from here?",60        config: {61          // Turn on grounding with Google Maps62          tools: [{ googleMaps: {} }],63          toolConfig: {64            retrievalConfig: {65              // Optionally provide the relevant location context (this is in Los Angeles)66              latLng: {67                latitude: 34.050481,68                longitude: -118.248526,69              },70            },71          },72        },73      });7475      console.log("Generated Response:");76      console.log(response.text);7778      const grounding = response.candidates[0]?.groundingMetadata;79      if (grounding?.groundingChunks) {80        console.log("-".repeat(40));81        console.log("Sources:");82        for (const chunk of grounding.groundingChunks) {83          if (chunk.maps) {84            console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`);85          }86        }87      }88    }8990    generateContentWithMapsGrounding();9192### REST9394    curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \95      -H 'Content-Type: application/json' \96      -H "x-goog-api-key: ${GEMINI_API_KEY}" \97      -d '{98      "contents": [{99        "role": "user",100        "parts": [{101          "text": "What are the best Italian restaurants within a 15-minute walk from here?"102        }]103      }],104      "tools": [{"googleMaps": {}}],105      "toolConfig": {106        "retrievalConfig": {107          "latLng": {"latitude": 34.050481, "longitude": -118.248526}108        }109      }110    }'111112## How Grounding with Google Maps works113114Grounding with Google Maps integrates the Gemini API with the Google Geo115ecosystem by using the Maps API as a grounding source. When a user's query116contains geographical context, the Gemini model can invoke the Grounding with117Google Maps tool. The model can then generate responses grounded in Google Maps118data relevant to the provided location.119120The process typically involves:1211221. **User query:** A user submits a query to your application, potentially including geographical context (e.g., "coffee shops near me," "museums in San Francisco").1232. **Tool invocation:** The Gemini model, recognizing the geographical intent, invokes the Grounding with Google Maps tool. This tool can optionally be provided with the user's `latitude` and `longitude`. The tool is a textual search tool and behaves similarly to searching on Maps, in that local queries ("near me") will use the coordinates, while specific or non-local queries are unlikely to be influenced by the explicit location.1243. **Data retrieval:** The Grounding with Google Maps service queries Google Maps for relevant information (e.g., places, reviews, photos, addresses, opening hours).1254. **Grounded generation:** The retrieved Maps data is used to inform the Gemini model's response, ensuring factual accuracy and relevance.1265. **Response:** The model returns a text response, which includes citations to Google Maps sources.127128## Why and when to use Grounding with Google Maps129130Grounding with Google Maps is ideal for applications that require accurate,131up-to-date, and location-specific information. It enhances the user experience132by providing relevant and personalized content backed by Google Maps' extensive133database of over 250 million places worldwide.134135You should use Grounding with Google Maps when your application needs to:136137- Provide complete and accurate responses to geo-specific questions.138- Build conversational trip planners and local guides.139- Recommend points of interest based on location and user preferences like restaurants or shops.140- Create location-aware experiences for social, retail, or food delivery services.141142Grounding with Google Maps excels in use cases where proximity and current143factual data are critical, such as finding the "best coffee shop near me" or144getting directions.145146## API methods and parameters147148Grounding with Google Maps is exposed through the Gemini API as a tool within149the [`generateContent`](https://ai.google.dev/api/generate-content) method. You enable and configure150Grounding with Google Maps by including a151[`googleMaps`](https://ai.google.dev/api/caching#GoogleMaps) object in the `tools` parameter of your152request.153154### JSON155156    {157      "contents": [{158        "parts": [159          {"text": "Restaurants near Times Square."}160        ]161      }],162      "tools":  { "googleMaps": {} }163    }164165Additionally, the tool supports passing the contextual location as `toolConfig`.166167### JSON168169    {170      "contents": [{171        "parts": [172          {"text": "Restaurants near here."}173        ]174      }],175      "tools":  { "googleMaps": {} },176      "toolConfig":  {177        "retrievalConfig": {178          "latLng": {179            "latitude": 40.758896,180            "longitude": -73.985130181          }182        }183      }184    }185186### Understanding the grounding response187188When a response is successfully grounded with Google Maps data, the response189includes a [`groundingMetadata`](https://ai.google.dev/api/generate-content#GroundingMetadata) field.190This structured data is essential for verifying claims and building a rich191citation experience in your application, as well as meeting the service usage192requirements.193194### JSON195196    {197      "candidates": [198        {199          "content": {200            "parts": [201              {202                "text": "CanteenM is an American restaurant with..."203              }204            ],205            "role": "model"206          },207          "groundingMetadata": {208            "groundingChunks": [209              {210                "maps": {211                  "uri": "https://maps.google.com/?cid=13100894621228039586",212                  "title": "Heaven on 7th Marketplace",213                  "placeId": "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"214                },215                // repeated ...216              }217            ],218            "groundingSupports": [219              {220                "segment": {221                  "startIndex": 0,222                  "endIndex": 79,223                  "text": "CanteenM is an American restaurant with a 4.6-star rating and is open 24 hours."224                },225                "groundingChunkIndices": [0]226              },227              // repeated ...228            ],229            "webSearchQueries": [230              "restaurants near me"231            ]232          }233        }234      ]235    }236237The Gemini API returns the following information with the238[`groundingMetadata`](https://ai.google.dev/api/generate-content#GroundingMetadata):239240- `groundingChunks`: Array of objects containing the `maps` sources (`uri`, `placeId` and `title`).241- `groundingSupports`: Array of chunks to connect model response text to the sources in `groundingChunks`. Each chunk links a text span (defined by `startIndex` and `endIndex`) to one or more `groundingChunkIndices`. This is the key to building inline citations.242243For a code snippet showing how to render inline citations in text, see [the244example](https://ai.google.dev/gemini-api/docs/google-search#attributing_sources_with_inline_citations)245in the Grounding with Google Search docs.246247## Use cases248249Grounding with Google Maps supports a variety of location-aware use cases. The250following examples demonstrate how different prompts and parameters can leverage251Grounding with Google Maps. Information in the Google Maps Grounded Results may252differ from actual conditions.253254### Handling place-specific questions255256Ask detailed questions about a specific place to get answers based on Google257user reviews and other Maps data.258259### Python260261    from google import genai262    from google.genai import types263264    client = genai.Client()265266    prompt = "Is there a cafe near the corner of 1st and Main that has outdoor seating?"267268    response = client.models.generate_content(269        model='gemini-3.8-flash',270        contents=prompt,271        config=types.GenerateContentConfig(272            # Turn on the Maps tool273            tools=[types.Tool(google_maps=types.GoogleMaps())],274275            # Provide the relevant location context (this is in Los Angeles)276            tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig(277                lat_lng=types.LatLng(278                    latitude=34.050481, longitude=-118.248526))),279        ),280    )281282    print("Generated Response:")283    print(response.text)284285    if grounding := response.candidates[0].grounding_metadata:286      if chunks := grounding.grounding_chunks:287        print('-' * 40)288        print("Sources:")289        for chunk in chunks:290          print(f'- [{chunk.maps.title}]({chunk.maps.uri})')291      ```292293### Javascript294295    import { GoogleGenAI } from '@google/genai';296297    const ai = new GoogleGenAI({});298299    async function run() {300      const prompt = "Is there a cafe near the corner of 1st and Main that has outdoor seating?";301302      const response = await ai.models.generateContent({303        model: 'gemini-3.8-flash',304        contents: prompt,305        config: {306          // Turn on the Maps tool307          tools: [{googleMaps: {}}],308          // Provide the relevant location context (this is in Los Angeles)309          toolConfig: {310            retrievalConfig: {311              latLng: {312                latitude: 34.050481,313                longitude: -118.248526314              }315            }316          }317        },318      });319320      console.log("Generated Response:");321      console.log(response.text);322323      const chunks = response.candidates[0].groundingMetadata?.groundingChunks;324      if (chunks) {325        console.log('-'.repeat(40));326        console.log("Sources:");327        for (const chunk of chunks) {328          if (chunk.maps) {329            console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`);330          }331        }332      }333    }334335    run();336337### REST338339    curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \340      -H 'Content-Type: application/json' \341      -H "x-goog-api-key: ${GEMINI_API_KEY}" \342      -d '{343      "contents": [{344        "role": "user",345        "parts": [{346          "text": "Is there a cafe near the corner of 1st and Main that has outdoor seating?"347        }]348      }],349      "tools": [{"googleMaps": {}}],350      "toolConfig": {351        "retrievalConfig": {352          "latLng": {"latitude": 34.050481, "longitude": -118.248526}353        }354      }355    }'356357### Providing location-based personalization358359Get recommendations tailored to a user's preferences and a specific geographical360area.361362### Python363364    from google import genai365    from google.genai import types366367    client = genai.Client()368369    prompt = "Which family-friendly restaurants near here have the best playground reviews?"370371    response = client.models.generate_content(372        model='gemini-3.8-flash',373        contents=prompt,374        config=types.GenerateContentConfig(375          tools=[types.Tool(google_maps=types.GoogleMaps())],376          tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig(377              # Provide the location as context; this is Austin, TX.378              lat_lng=types.LatLng(379                  latitude=30.2672, longitude=-97.7431))),380        ),381    )382383    print("Generated Response:")384    print(response.text)385386    if grounding := response.candidates[0].grounding_metadata:387      if chunks := grounding.grounding_chunks:388        print('-' * 40)389        print("Sources:")390        for chunk in chunks:391          print(f'- [{chunk.maps.title}]({chunk.maps.uri})')392393### Javascript394395    import { GoogleGenAI } from '@google/genai';396397    const ai = new GoogleGenAI({});398399    async function run() {400      const prompt = "Which family-friendly restaurants near here have the best playground reviews?";401402      const response = await ai.models.generateContent({403        model: 'gemini-3.8-flash',404        contents: prompt,405        config: {406          tools: [{googleMaps: {}}],407          toolConfig: {408            retrievalConfig: {409              // Provide the location as context; this is Austin, TX.410              latLng: {411                latitude: 30.2672,412                longitude: -97.7431413              }414            }415          }416        },417      });418419      console.log("Generated Response:");420      console.log(response.text);421422      const chunks = response.candidates[0].groundingMetadata?.groundingChunks;423      if (chunks) {424        console.log('-'.repeat(40));425        console.log("Sources:");426        for (const chunk of chunks) {427          if (chunk.maps) {428            console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`);429          }430        }431      }432    }433434    run();435436### REST437438    curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \439      -H 'Content-Type: application/json' \440      -H "x-goog-api-key: ${GEMINI_API_KEY}" \441      -d '{442      "contents": [{443        "role": "user",444        "parts": [{445          "text": "Which family-friendly restaurants near here have the best playground reviews?"446        }],447      }],448      "tools": [{"googleMaps": {}}],449      "toolConfig": {450        "retrievalConfig": {451          "latLng": {"latitude": 30.2672, "longitude": -97.7431}452        }453      }454    }'455456### Assisting with itinerary planning457458Generate multi-day plans with directions and information about various459locations, perfect for travel applications.460461### Python462463    from google import genai464    from google.genai import types465466    client = genai.Client()467468    prompt = "Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner."469470    response = client.models.generate_content(471        model='gemini-3.8-flash',472        contents=prompt,473        config=types.GenerateContentConfig(474          tools=[types.Tool(google_maps=types.GoogleMaps())],475          tool_config=types.ToolConfig(retrieval_config=types.RetrievalConfig(476              # Provide the location as context, this is in San Francisco.477              lat_lng=types.LatLng(478                  latitude=37.78193, longitude=-122.40476))),479        ),480    )481482    print("Generated Response:")483    print(response.text)484485    if grounding := response.candidates[0].grounding_metadata:486      if grounding.grounding_chunks:487        print('-' * 40)488        print("Sources:")489        for chunk in grounding.grounding_chunks:490          print(f'- [{chunk.maps.title}]({chunk.maps.uri})')491492### Javascript493494    import { GoogleGenAI } from '@google/genai';495496    const ai = new GoogleGenAI({});497498    async function run() {499      const prompt = "Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner.";500501      const response = await ai.models.generateContent({502        model: 'gemini-3.8-flash',503        contents: prompt,504        config: {505          tools: [{googleMaps: {}}],506          toolConfig: {507            retrievalConfig: {508              // Provide the location as context, this is in San Francisco.509              latLng: {510                latitude: 37.78193,511                longitude: -122.40476512              }513            }514          }515        },516      });517518      console.log("Generated Response:");519      console.log(response.text);520521      const groundingMetadata = response.candidates[0]?.groundingMetadata;522      if (groundingMetadata) {523        if (groundingMetadata.groundingChunks) {524          console.log('-'.repeat(40));525          console.log("Sources:");526          for (const chunk of groundingMetadata.groundingChunks) {527            if (chunk.maps) {528              console.log(`- [${chunk.maps.title}](${chunk.maps.uri})`);529            }530          }531        }532      }533    }534535    run();536537### REST538539    curl -X POST 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent' \540      -H 'Content-Type: application/json' \541      -H "x-goog-api-key: ${GEMINI_API_KEY}" \542      -d '{543      "contents": [{544        "role": "user",545        "parts": [{546          "text": "Plan a day in San Francisco for me. I want to see the Golden Gate Bridge, visit a museum, and have a nice dinner."547        }]548      }],549      "tools": [{"googleMaps": {}}],550      "toolConfig": {551        "retrievalConfig": {552        "latLng": {"latitude": 37.78193, "longitude": -122.40476}553      }554      }555    }'556557## Service usage requirements558559This section describes the service usage requirements for Grounding with Google560Maps.561562### Inform the user about the use of Google Maps sources563564With each Google Maps Grounded result, you'll receive sources in565`groundingChunks` that support each response. The following metadata is also566returned:567568- source uri569- title570- ID571572When presenting results from Grounding with Google Maps, you must specify the573associated Google Maps sources, and inform your users of the following:574575- The Google Maps sources must immediately follow the generated content that the sources support. This generated content is also referred to as Google Maps Grounded Result.576- The Google Maps sources must be viewable within one user interaction.577578### Display Google Maps sources with Google Maps links579580For each source in `groundingChunks` and in581`grounding_chunks.maps.placeAnswerSources.reviewSnippets`, a link preview must582be generated following these requirements:583584- Attribute each source to Google Maps following the Google Maps text [attribution guidelines](https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding#maps-attribution-guidelines).585- Display the source title provided in the response.586- Link to the source using the `uri` or `googleMapsUri` from the response.587588These images show the minimum requirements for displaying the sources and Google589Maps links.590591![Prompt with response showing sources](https://ai.google.dev/static/gemini-api/docs/images/maps/sources-expanded.jpg)592593You can collapse the view of the sources.594595![Prompt with response and sources collapsed](https://ai.google.dev/static/gemini-api/docs/images/maps/sources-collapsed.jpg)596597Optional: Enhance the link preview with additional content, such as:598599- A [Google Maps favicon](https://www.google.com/images/branding/product/ico/web_maps_icon_32dp.ico) is inserted before the Google Maps text attribution.600- A photo from the source URL (`og:image`).601602For more information about some of our Google Maps data providers and their603license terms, see the [Google Maps and Google Earth legal notices](https://www.google.com/help/legalnotices_maps/).604605### Google Maps text attribution guidelines606607When you attribute sources to Google Maps in text, follow these guidelines:608609- Don't modify the text Google Maps in any way:610  - Don't change the capitalization of Google Maps.611  - Don't wrap Google Maps onto multiple lines.612  - Don't localize Google Maps into another language.613  - Prevent browsers from translating Google Maps by using the HTML attribute translate="no".614- Style Google Maps text as described in the following table:615616| Property | Style |617|---|---|618| `Font family` | Roboto. Loading the font is optional. |619| `Fallback font family` | Any sans serif body font already used in your product or "Sans-Serif" to invoke the default system font |620| `Font style` | Normal |621| `Font weight` | 400 |622| `Font color` | White, black (#1F1F1F), or gray (#5E5E5E). Maintain accessible (4.5:1) contrast against the background. |623| `Font size` | - Minimum font size: 12sp - Maximum font size: 16sp - To learn about sp, see Font size units on the [Material Design website](https://m3.material.io/styles/typography/type-scale-tokens#3f4488e7-3b74-45b0-a143-9d6afa4d62dc). |624| `Spacing` | Normal |625626#### Example CSS627628The following CSS renders Google Maps with the appropriate typographic style and629color on a white or light background.630631### CSS632633    @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');634635    .GMP-attribution {636637    font-family: Roboto, Sans-Serif;638    font-style: normal;639    font-weight: 400;640    font-size: 1rem;641    letter-spacing: normal;642    white-space: nowrap;643    color: #5e5e5e;644    }645646### Place ID and review ID647648The Google Maps data includes place ID and review ID. You might649cache, store, and export the following response data:650651- `placeId`652- `reviewId`653654The restrictions against caching in the Grounding with Google Maps Terms don't655apply.656657### Prohibited activity and territory658659Grounding with Google Maps has additional restrictions for certain content and660activities to maintain a safe and reliable platform. In addition to the usage661restrictions in the [Terms](https://ai.google.dev/gemini-api/terms#grounding-with-google-maps):662663- You won't use Grounding with Google Maps for high risk activities including emergency response services.664- You won't distribute or market your application that offers Grounding with Google Maps in a Prohibited Territory. For more information, see [Google Maps Platform Prohibited Territories](https://cloud.google.com/maps-platform/terms/maps-prohibited-territories). The list of Prohibited Territories may be updated from time to time.665666## Best practices667668- **Provide user location:** For the most relevant and personalized responses, always include the `user_location` (latitude and longitude) in your `googleMapsGrounding` configuration when the user's location is known.669- **Inform End-Users:** Clearly inform your end-users that Google Maps data is being used to answer their queries, especially when the tool is enabled.670- **Monitor Latency:** For conversational applications, ensure that the P95 latency for grounded responses remains within acceptable thresholds to maintain a smooth user experience.671- **Toggle Off When Not Needed:** Grounding with Google Maps is off by default. Only enable it (`"tools": [{"googleMaps": {}}]`) when a query has a clear geographical context, to optimize performance and cost.672673## Limitations674675- **Geographical Scope:** Grounding with Google Maps is globally available676- **Model Support:** See the [Supported models](https://ai.google.dev/gemini-api/docs/generate-content/maps-grounding#supported-models) section.677- **Multimodal Inputs/Outputs:** Grounding with Google Maps does not currently support multimodal inputs or outputs beyond text.678- **Default State:** The Grounding with Google Maps tool is off by default. You must explicitly enable it in your API requests.679680## Pricing and rate limits681682Grounding with Google Maps pricing is based on queries. The current rate is683**$25 / 1K grounded prompts**. The free tier also has up to 500 requests per day684available. A request is only counted towards the quota when685a prompt successfully returns at least one Google Maps grounded result (i.e.,686results containing at least one Google Maps source). If multiple queries are687sent to Google Maps from a single request, it counts as one request towards the688rate limit.689690> [!NOTE]691> **Note:** The quota for Grounding with Google Maps typically aligns with the underlying Gemini model rate limits.692693For detailed pricing information, see the [Gemini API pricing page](https://ai.google.dev/gemini-api/docs/pricing).694695## Supported models696697The following models support Grounding with Google Maps:698699| Model | Grounding with Google Maps |700|---|---|701| [Gemini 3.8 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash) | ✔️ |702| [Gemini 3.7 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.7-flash) | ✔️ |703| [Gemini 3.6 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.6-flash) | ✔️ |704| [Gemini 3.5 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash-lite) | ✔️ |705| [Gemini 3.5 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-3.5-flash) | ✔️ |706| [Gemini 3.1 Pro Preview](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-pro-preview) | ✔️ |707| [Gemini 3.1 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-lite) | ✔️ |708| [Gemini 3 Flash Preview](https://ai.google.dev/gemini-api/docs/models/gemini-3-flash-preview) | ✔️ |709| [Gemini 2.5 Pro](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-pro) | ✔️ |710| [Gemini 2.5 Flash](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash) | ✔️ |711| [Gemini 2.5 Flash-Lite](https://ai.google.dev/gemini-api/docs/models/gemini-2.5-flash-lite) | ✔️ |712713## Supported tool combinations714715You can use Grounding with Google Maps with other built-in tools like716[Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search) (supported on717Gemini 3.5 Flash and later models) to power more complex use cases. Gemini 3718models also support combining these built-in tools with custom tools (function719calling). Learn more on the720[tool combinations](https://ai.google.dev/gemini-api/docs/tool-combination) page.721722## What's next723724- Try the [Grounding with Google Search in the Gemini API725  Cookbook](https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Search_Grounding.ipynb).726- Learn about other [available tools](https://ai.google.dev/gemini-api/docs/tools).727- To learn more about responsible AI best practices and Gemini API's safety filters, see [the Safety settings guide](https://ai.google.dev/gemini-api/docs/safety-settings).
Files main
Menu

Theme