# Grounding with Google Maps

Grounding with Google Maps connects a Gemini model to geospatial data from Google Maps so that you can build location-aware functionality into your apps.

## Supported models
- `gemini-3.1-pro-preview`
- `gemini-3.8-flash` (and the older `gemini-3.7-flash`, `gemini-3.6-flash`, and `gemini-3.5-flash`)
- `gemini-3.5-flash-lite` (and the older `gemini-3.1-flash-lite`)

General-use Gemini 2.5 models support this capability, but they're all deprecated.

## Ground the model with Google Maps

|     |
| --- |
| _Click your Gemini API provider to view provider-specific content_<br>_and code on this page._<br>Gemini Developer APIAgent Platform Gemini API |

When you create the `GenerativeModel` instance, provide `GoogleMaps` as a `tool` that the model can use to generate its response.

```swift
import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Example: Coordinates for New York City
let latAndLong = CLLocationCoordinate2D(latitude: 40.7128, longitude: -74.0060)

// (Optional) Define a RetrievalConfig to configure the Grounding with Google Maps tool.
let retrievalConfig = RetrievalConfig(
    location: latAndLong,
    languageCode: "en-US"
)

// Wrap the RetrievalConfig inside a ToolConfig.
let toolConfig = ToolConfig(retrievalConfig: retrievalConfig)

// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(
    modelName: "GEMINI_MODEL_NAME",
    tools: [Tool.googleMaps()],
    toolConfig: toolConfig
)

let response = try await model.generateContent("restaurants near me?")
print(response.text ?? "No text in response.")
```

### Grounding with Google Maps has the following benefits:
- **Increase factual accuracy**: Reduce model hallucinations by basing responses on Google's database of over 250 million real-world places and businesses.
- **Access real-time information**: Answer questions using live data, such as current business hours and the real-time status of EV charging stations.
- **Provide sources**: Build user trust by showing Google Maps place sources and links directly alongside the model's location-based claims.

## Best practices and tips to improve results
This section describes some general best practices for using Grounding with Google Maps, as well as how to take advantage of _place properties_ to improve results.

### General best practices
- **Only provide the tool when needed**: To optimize performance and cost, provide the model with access to the Grounding with Google Maps tool only when the use case has a clear geographical context.
- **Provide user location**: For the most relevant and personalized responses (and when the user's location is known), include the user's location (using latitude and longitude via `latLng`) in the Grounding with Google Maps tool configuration.
- **Inform end users**: Clearly inform your end users that Google Maps data is being used to answer their queries. Providing end users with the sources from Google Maps is a service usage requirement for the Grounding with Google Maps tool.

### Use place properties in prompts
This section lists **place properties** that are used to describe locations and are used by Grounding with Google Maps to generate responses.

#### Sample place properties
- Address
- Curbside pickup
- Debit card
- Distance
- Free parking lot
- Live music
- Menu for children
- Opening hours
- Payment options (such as _cash_ or _credit card_)
- Pet friendly
- Serves beer
- Serves vegetarian food
- Wheelchair accessible
- Wifi

#### Example prompts that use place properties
- **Plan a family dinner**: Determine if a restaurant is suitable for a family and if the restaurant offers a convenient service.
  - Example prompt: _Is "The Italian Place" good for children, and do they offer takeout? What is their rating?_
- **Check accessibility for a friend**: Determine if the location meets specific accessibility needs.
  - Example prompt: _I need a restaurant that has a wheelchair accessible entrance._
- **Find a location for a late-night snack**: Find an open establishment serving a specific meal during a particular time.
  - Example prompt: _Is "Burger Joint" open now? Do they serve dinner? What are their opening hours for Friday?_
- **Meet a client for coffee**: Assess the suitability of a cafe for a business meeting based on amenities, offerings, and payment options.
  - Example prompt: _Does "Cafe Central" have Wifi? Do they serve coffee? What is their price level, and do they accept credit cards?_

### How Grounding with Google Maps works
When you provide the model with the `GoogleMaps` tool, the model handles the entire workflow of searching, processing, and citing information automatically.

Here's the workflow of the _model_:
1. **Receives prompt**: Your app sends a prompt to the Gemini model with the `GoogleMaps` tool enabled.
2. **Analyzes prompt**: The model analyzes the prompt and determines if Google Maps can improve its response.
3. **Invokes the tool**: The model, recognizing the geographical intent, invokes the Grounding with Google Maps tool.
4. **Sends queries to Google Maps**: The Grounding with Google Maps service queries Google Maps for relevant information.
5. **Processes the Google Maps results**: The model processes the Google Maps results and formulates a response to the original prompt.
6. **Returns a _Google Maps Grounded Result_**: The model returns a final, user-friendly response that is grounded in the Google Maps results.

### Understand the grounded result
If the model grounds its response in Google Maps results, then the response includes a `groundingMetadata` object that contains structured data.

#### Example response that includes a `groundingMetadata` object:
```json
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "CanteenM is an American restaurant with..."
          }
        ],
        "role": "model"
      },
      "groundingMetadata": {
        "groundingChunks": [
          {
            "maps": {
              "uri": "https://maps.google.com/?cid=13100894621228039586",
              "title": "Heaven on 7th Marketplace",
              "placeId": "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
            }
          }
        ],
        "groundingSupports": [
          {
            "segment": {
              "startIndex": 0,
              "endIndex": 79,
              "text": "CanteenM is an American restaurant with a 4.6-star rating and is open 24 hours."
            },
            "groundingChunkIndices": [0]
          }
        ]
      }
    }
  ]
}
```

## Service usage requirements
This section describes the service usage requirements for Grounding with Google Maps for your chosen Gemini API provider.

### Inform users of Google Maps sources
With each _Google Maps Grounded Result_, you'll receive sources in `groundingChunks` that support each response. The following metadata is also returned:
- source uri
- title
- ID

### Pricing and rate limits
Grounding with Google Maps pricing is based on queries. A request is only counted towards the Google Maps quota when a prompt successfully returns at least one _Google Maps Grounded Result_.
