依托 Google 地图进行接地

借助“依托 Google Maps 进行接地”,可以将 Gemini 模型连接到 Google Maps 中的地理空间 数据,以便您在应用中构建具有位置感知功能的功能 。

“依托 Google Maps 进行接地”具有以下优势:

  • 提高事实准确性:依托 Google 超过 2.5 亿个真实地点和商家组成的数据库来生成 回答,减少模型幻觉。
  • 访问实时信息:使用实时数据(例如 当前营业时间和电动汽车充电站的实时状态)回答问题。
  • 提供视觉背景信息:将互动式地图 widget、照片和街景视图直接与模型的 基于位置的声明集成,从而建立用户信任。

支持的模型

  • gemini-3.1-pro-preview
  • gemini-3.7-flash(以及较旧的 gemini-3.6-flashgemini-3.5-flash
  • gemini-3.5-flash-lite(以及较旧的 gemini-3.1-flash-lite

通用 Gemini 2.5 模型支持此 功能,但它们都已废弃。

支持的语言

请参阅 支持的语言 (适用于 Gemini 模型)。

使用 Google Maps 连接模型

点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容 和代码。

创建 GenerativeModel 实例时,请提供 GoogleMaps 作为模型可用于生成回答的 tool

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.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
let retrievalConfig = RetrievalConfig(
    location: latAndLong,
    // Example: Language code for English (US).
    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",
    // Provide Google Maps as a tool that the model can use to generate its response.
    tools: [Tool.googleMaps()],
    // Add the configuration for the Grounding with Google Maps tool
    // (if this optional config was defined above).
    toolConfig: toolConfig
)

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

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

Kotlin


// (Optional) Define a RetrievalConfig to configure the Grounding with Google Maps tool.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
val retrievalConfig = RetrievalConfig(
    // Example: Coordinates for New York City
    latLng = LatLng(latitude = 40.7128, longitude = -74.0060),
    // Example: Language code for English (US)
    languageCode = "en_US"
)

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

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Add the configuration for the Grounding with Google Maps tool
    // (if this optional config was defined above).
    toolConfig = toolConfig,
    // Provide Google Maps as a tool that the model can use to generate its response.
    tools = listOf(Tool.googleMaps())
)

val response = model.generateContent("restaurants near me?")
print(response.text)

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

Java


// (Optional) Define a ToolConfig to configure the Grounding with Google Maps tool.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
ToolConfig toolConfig = new ToolConfig(
    null,
    new RetrievalConfig(
        // Example: Coordinates for New York City.
        new LatLng(40.7128, -74.0060),
        // Example: Language code for English (US).
       "en_US"
    )
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide Google Maps as a tool that the model can use to generate its response.
                        List.of(Tool.googleMaps()),
                        // Add the configuration for the Grounding with Google Maps tool
                        // (if this optional config was defined above).
                        toolConfig);

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

ListenableFuture response = model.generateContent("restaurants near me?");
  Futures.addCallback(response, new FutureCallback() {
      @Override
      public void onSuccess(GenerateContentResponse result) {
          String resultText = result.getText();
          System.out.println(resultText);
      }

      @Override
      public void onFailure(Throwable t) {
          t.printStackTrace();
      }
  }, executor);

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// (Optional) Define a toolConfig to configure the Grounding with Google Maps tool.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
const toolConfig = {
  retrievalConfig: {
    // Example: Coordinates for New York City
    latLng: {
      latitude: 40.7128,
      longitude: -74.0060
    },
    // Example: Language code for English (US)
    languageCode: 'en-US'
  }
};

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide Google Maps as a tool that the model can use to generate its response.
    // (Optional) Set `enableWidget` to control whether the response contains a `googleMapsWidgetContextToken`.
    tools: [ { googleMaps: { enableWidget: true } } ],
    // Add the configuration for the Grounding with Google Maps tool
    // (if this optional config was defined above).
    toolConfig
  }
);

const result = await model.generateContent("restaurants near me?");

console.log(result.response.text());

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

Dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ai/firebase_ai.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp.
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// (Optional) Define a ToolConfig to configure the Grounding with Google Maps tool.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
final toolConfig = ToolConfig(
  retrievalConfig: RetrievalConfig(
    // Example: Coordinates for New York City.
    latLng: LatLng(latitude: 40.712728, longitude: -74.006015),
    // Example: Language code for English (US).
    languageCode: 'en',
  ),
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'GEMINI_MODEL_NAME',
  // Provide Google Maps as a tool that the model can use to generate its response.
  tools: [
    Tool.googleMaps(),
  ],
  // Add the configuration for the Grounding with Google Maps tool
  // (if this optional config was defined above).
  toolConfig: toolConfig,
);

final response = await model.generateContent([Content.text("restaurants near me?")]);
print(response.text);

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Example: Coordinates for New York City
var latLng = new LatLng(40.7128, -74.0060);

// (Optional) Define a RetrievalConfig to configure the Grounding with Google Maps tool.
// You can optionally provide a location's coordinates and/or a language code
// for more relevant and personalized Google Maps results.
var retrievalConfig = new RetrievalConfig(latLng, languageCode: "en");

// Wrap the RetrievalConfig inside a ToolConfig.
var toolConfig = new ToolConfig(retrievalConfig: retrievalConfig);

// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide Google Maps as a tool that the model can use to generate its response.
  tools: new[] { new Tool(new GoogleMaps()) },
  // Add the configuration for the Grounding with Google Maps tool
  // (if this optional config was defined above).
  toolConfig: toolConfig
);

var response = await model.GenerateContentAsync("restaurants near me?");
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

// Make sure to comply with the "Grounding with Google Maps" usage requirements,
// which includes how you meet service usage requirements

了解如何选择适合您的用例和应用的模型 (可选)。

有关改进结果的最佳实践和提示

本部分介绍了一些使用“依托 Google Maps进行接地”的一般最佳实践,以及如何利用 地点属性来改进 结果。

一般最佳实践

  • 仅在需要时提供工具:为了优化性能和费用, 仅当用例具有明确的地理背景信息时,才向模型提供对“依托 Google Maps 工具进行接地”工具的访问权限。

  • 提供用户位置信息:为了获得最相关且个性化的回答 (以及在已知用户位置信息的情况下),请在“依托 Google Maps ”工具配置中添加用户位置信息(使用 纬度和经度,通过 latLng)。

  • 告知最终用户:明确告知最终用户,系统正在使用 Google Maps 数据 来回答他们的查询。向最终用户提供来自 Google Maps 的来源 是“依托 Google Maps 进行接地”工具的 服务使用要求

  • (仅限 Web SDK) 渲染Google Maps上下文相关微件:上下文相关微件使用上下文令牌googleMapsWidgetContextToken 进行渲染,该令牌在 Gemini API 回答中返回,可用于渲染 Google Maps 中的视觉内容。如需详细了解上下文相关 widget,请参阅 依托 Google Maps widget 文档。Google Maps

在提示中使用地点属性

本部分列出了用于描述地点并由“依托 Google Maps 进行接地”用于生成回答的 地点属性 。这些属性 用于确定“依托 Google Maps 进行接地”可以回答的问题类型。

地点属性示例

此列表按字母顺序提供了有关地点的属性样本,您的模型可以使用这些属性来生成回答。

  • 地址
  • 路边自提
  • 借记卡
  • 距离
  • 免费停车场
  • 现场音乐表演
  • 儿童菜单
  • 营业时间
  • 付款方式(例如现金或信用卡
  • 地点回答
  • 允许带宠物
  • 供应啤酒
  • 供应素食
  • 有无障碍设施
  • Wifi

地点回答 是“依托 Google Maps 进行接地”根据 从用户评价中提取的信息生成的回答。

使用地点属性的提示示例

以下示例在有关不同类型地点的提示中使用了 地点属性 。借助“依托 Google Maps 进行接地”,可使用 这些属性来了解您的意图,然后根据与 Google Maps 中地点关联的数据提供相关回答 。

  • 计划家庭晚餐:确定餐厅是否适合 家庭用餐,以及餐厅是否提供便捷的服务。

    • 提示示例: “The Italian Place”适合儿童吗?他们提供外卖服务吗?他们的评分是多少?
  • 为好友查询无障碍设施:确定地点是否满足 特定的无障碍需求。

    • 提示示例: 我需要一家有轮椅无障碍入口的餐厅。
  • 寻找可以吃夜宵的地方:找到在特定时间段内提供特定餐点的 营业场所。

    • 提示示例: “Burger Joint”现在营业吗?他们提供晚餐吗? 他们周五的营业时间是几点?
  • 与客户相约喝咖啡:根据咖啡馆的酒店设施、供应的商品和支付方式,评估咖啡馆是否适合商务会议。

    • 提示示例: “Cafe Central”有 Wi-Fi 吗?他们供应咖啡吗? 这些餐厅的价位如何?是否接受信用卡?

请注意,Google Maps接地结果中的信息可能与实际路况有所不同 。

“依托 Google Maps 进行接地”的工作原理

当您向模型提供 GoogleMaps 工具时,模型会自动处理搜索、处理和引用信息的整个工作流程。

以下是 模型的工作流程:

  1. 接收提示:您的应用会向启用了 GoogleMaps工具的 Gemini 模型发送提示。

  2. 分析提示:模型会分析提示,并确定 Google Maps是否可以改进其回答,例如,提示是否 包含地理背景信息(例如“我附近的咖啡馆”“ 旧金山的博物馆”)。

  3. 调用工具:模型识别出地理意图,并 调用“依托 Google Maps 进行接地”工具。

  4. Google Maps发送查询**:“依托 Google Maps 服务会向 Google Maps 查询相关信息(例如 地点、评价、照片、地址、营业时间)。

    您可以选择在工具的配置中 (甚至直接在提示中)添加纬度和经度,以获得更相关且个性化的 Google Maps结果。该工具是一个文本搜索工具,其行为 与在 Google Maps 上搜索类似,即本地查询(“我附近”) 将使用坐标,而特定或非本地查询不太可能 受到明确位置的影响。

  5. 处理 Google Maps 结果 :模型会处理 Google Maps 结果,并针对原始提示制定回答。

  6. 返回Google Maps接地结果:模型会返回一个最终的 用户友好的回答,该回答基于Google Maps结果。 此回答包括:

    • 模型的文本回答。
    • 包含 Google Maps 结果和 来源的 groundingMetadata 对象。
    • (仅限 Web SDK)可选的 googleMapsWidgetContextToken,可让您 在应用中渲染上下文相关的 Google Maps widget,以进行视觉 互动。如需详细了解上下文相关 widget,请参阅 “依托 Google Maps widget ”文档。Google Maps

请注意,向模型提供 Google Maps 作为工具 并不要求 模型始终使用 Google Maps 工具来生成回答。在 这些情况下,回答不会包含 groundingMetadata 对象,因此 它不是 Google Maps 接地结果

了解接地结果

如果模型基于 Google Maps 结果生成回答,则回答 会包含 groundingMetadata 对象,其中包含结构化数据,这些数据 对于验证声明和在应用中构建丰富的来源体验至 101}关重要。

Google Maps 接地结果中的 groundingMetadata 对象包含 以下信息:

  • groundingChunks:包含 maps 来源(uriplaceIdtitle)的对象数组。
  • groundingSupports:用于将模型回答 text 连接到 groundingChunks 中的来源的块数组。每个块都会将文本 segment(由 startIndexendIndex 定义)链接到一个或多个 groundingChunkIndices。此字段可帮助您构建内嵌来源链接。 本页面的后面部分会介绍如何 满足服务使用要求
  • (仅限 Web SDK) googleMapsWidgetContextToken:可用于渲染 上下文相关的 Places widget 的文本 token。 仅在使用 Web SDK 且已将 enableWidget 参数设置为 true 时,系统才会返回此字段。

以下是包含 groundingMetadata 对象的回答示例:

{
  "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]
          }
        ],
        "googleMapsWidgetContextToken": "widgetcontent/..."
      }
    }
  ]
}

服务使用要求

本部分介绍了您选择的 Gemini API 提供方( Gemini Developer APIAgent Platform Gemini API (formerly Vertex AI))的“依托 Google Maps进行接地”服务使用要求(请参阅《服务专用条款》中的 “服务条款” 部分)。

告知用户 Google Maps 来源

对于每个 Google Maps 接地结果,您都会收到 groundingChunks 中支持相应回答的来源。系统还会返回以下元数据:

  • 源 URI
  • 标题
  • ID

在应用中呈现“依托 Google Maps 进行接地”的结果时,您 必须指定关联的 Google Maps 来源,并告知用户以下信息:

  • Google Maps 来源必须紧跟在来源支持的生成内容 之后。此类生成的内容也称为 Google Maps接地结果

  • Google Maps 来源必须在一次用户互动中可见。

以下介绍了如何获取值以显示 Google Maps接地结果中的来源:

Swift

// ...

// Get the model's response
let text = response.text

// Get the grounding metadata
if let candidate = response.candidates.first,
   let groundingMetadata = candidate.groundingMetadata {

  // Get sources
  let groundingChunks = groundingMetadata.groundingChunks
  for chunk in groundingChunks {
    if let maps = chunk.maps {
      let title = maps.title  // for example, "Heaven on 7th Marketplace"
      let url = maps.url  // for example, "https://maps.google.com/?cid=13100894621228039586"
      let placeId