利用 Google 地圖建立基準

透過 Google Maps 建立基準,可將 Gemini 模型連結至 Google Maps 的地理空間資料,以便在應用程式中建構位置感知功能。

使用 Google Maps 建立基準有下列好處:

  • 提高事實準確度:根據 Google 資料庫中超過 2.5 億個真實地點和商家資訊,減少模型幻覺。
  • 存取即時資訊:使用即時資料回答問題,例如目前的營業時間和電動車充電站的即時狀態。
  • 提供來源:在模型根據位置提出的主張旁,直接顯示 Google Maps 地點來源和連結,建立使用者信任感。

支援的模型

  • gemini-4-argon
  • gemini-3.8-flash
  • gemini-3.5-flash-lite (以及舊版 gemini-3.1-flash-lite)

舊版一般用途 Gemini 3.x Flash 模型支援這項功能,但由於即將停用和/或自動轉送至新版模型,因此不建議使用。

支援的語言

查看 Gemini 模型支援的語言。

使用 Google Maps 建立模型基準

按一下您的Gemini API供應商,即可在這個頁面上查看供應商專屬內容和程式碼。

建立 GenerativeModel 執行個體時,請提供 GoogleMaps 做為 tool,供模型用於生成回覆。

Swift


import CoreLocation
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: [.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.
    tools: [ { googleMaps: {} } ],
    // 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-US',
  ),
);

// 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建立基準」工具的服務使用規定。

在提示中使用地點屬性

本節列出用於描述位置的地點屬性,以及Google Maps基準化功能用於生成回覆的屬性。這些屬性可用來判斷「使用 Google Maps 建立基準」功能可回答的問題類型。

地點屬性範例

這份清單依字母順序提供地點屬性範例,模型可使用這些屬性生成回覆。

  • 地址
  • 店外取貨
  • 簽帳金融卡
  • 距離
  • 免費停車位
  • 提供現場音樂演奏
  • 兒童菜單
  • 服務時間
  • 付款方式 (例如現金或信用卡)
  • 有關地點的回答
  • 寵物友善
  • 供應啤酒
  • 供應素食料理
  • 有無障礙設施
  • Wifi

地點答案是 Grounding with Google Maps 根據使用者評論資訊提供的回覆。

使用地點屬性的提示範例

下列範例在提示中使用地點屬性,查詢不同類型的地點。使用 Google Maps 建立基準時,系統會根據屬性瞭解您的意圖,然後根據 Google Maps 中與地點相關聯的資料,提供相關答案。

  • 規劃家庭聚餐:判斷餐廳是否適合家庭聚餐,以及是否提供便利服務。

    • 提示範例:「The Italian Place」適合帶小孩去嗎?有提供外帶服務嗎?評分是多少?
  • 為朋友查看無障礙設施:判斷地點是否符合特定無障礙需求。

    • 提示範例:我需要找有輪椅無障礙入口的餐廳。
  • 尋找吃宵夜的地點:尋找在特定時間營業並供應特定餐點的商家。

    • 提示範例:「Burger Joint」現在有營業嗎?有供應晚餐嗎? 他們週五的營業時間為何?
  • 與客戶喝咖啡:根據設施、餐點和付款方式,評估咖啡廳是否適合舉辦商務會議。

    • 提示範例:「Cafe Central」有 Wi-Fi 嗎?Do they serve coffee? 價位為何?是否接受信用卡?

請注意,Google Maps Grounded Results 中的資訊可能與實際路況不同。

Google Maps 建立基準的運作方式

提供 GoogleMaps 工具給模型後,模型會自動處理搜尋、處理和引用資訊的整個工作流程。

以下是模型的工作流程:

  1. 接收提示:應用程式向 Gemini 模型傳送提示,並啟用 GoogleMaps 工具。

  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 物件。

請注意,將 Google Maps 做為工具提供給模型,不代表模型一律會使用 Google Maps 工具生成回覆。在這種情況下,回應不會包含 groundingMetadata 物件,因此不是Google Maps 基準結果。

瞭解基準化結果

如果模型根據 Google Maps 結果建立回覆,回覆會包含 groundingMetadata 物件,其中含有結構化資料,可用於驗證聲明,並在應用程式中建立豐富的來源體驗。

Google Maps有基準的結果中的 groundingMetadata 物件包含下列資訊:

  • groundingChunks:包含 maps 來源 (uri、placeId 和 title) 的物件陣列。
  • groundingSupports:區塊陣列,用於將模型回覆 text 連結至 groundingChunks 中的來源。每個區塊都會將文字 segment (由 startIndex 和 endIndex 定義) 連結至一或多個 groundingChunkIndices。這個欄位可協助您建立內嵌來源連結。請參閱本頁後續內容,瞭解如何符合服務使用規定。

以下是包含 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]
          }
        ]
      }
    }
  ]
}

服務使用規定

本節說明使用Google Maps建立基準時,您選擇的Gemini API供應商必須遵守的服務使用規定:Gemini Developer API或Agent Platform Gemini API (formerly Vertex AI) (請參閱《服務專屬條款》中的「服務條款」一節)。

告知使用者 Google Maps 來源

每個Google Maps基準結果都會提供 groundingChunks 來源,佐證各項回覆。系統也會傳回下列中繼資料:

  • 來源 URI
  • title
  • ID

在應用程式中,使用 Google Maps 建立基準並呈現結果時,必須指定相關聯的 Google Maps 來源,並向使用者說明下列事項:

  • Google Maps 來源必須緊接在支援的生成內容之後。這類生成內容也稱為Google Maps基準化結果。

  • 使用者必須能透過一次互動,查看所有 Google Maps 來源。

如要取得 Google Maps Grounded Result 的來源顯示值,請按照下列步驟操作:

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 = maps.placeID  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
      // TODO(developer): show source in the UI
    }
  }
}

Kotlin

// ...

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

// Get the grounding metadata
val groundingMetadata = response.candidates.firstOrNull()?.groundingMetadata

// Get sources
val groundingChunks = groundingMetadata?.groundingChunks
groundingChunks?.let { chunks ->
  for (chunk in chunks) {
    val title = chunk.maps?.title  // for example, "Heaven on 7th Marketplace"
    val uri = chunk.maps?.uri  // for example, "https://maps.google.com/?cid=13100894621228039586"
    val placeId = chunk.maps?.placeId  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
    // TODO(developer): show source in the UI
  }
}

Java

// ...

Futures.addCallback(response, new FutureCallback() {
  @Override
  public void onSuccess(GenerateContentResponse result) {
    // Get the model's response
    String text = result.getText();

    // Get the grounding metadata
    GroundingMetadata groundingMetadata =
        result.getCandidates()[0].getGroundingMetadata();

    if (groundingMetadata != null) {
      // Get sources
      List chunks = groundingMetadata.getGroundingChunks();
      if (chunks != null) {
        for(GroundingChunk chunk : chunks) {
          GoogleMapsGroundingChunk maps = chunk.getMaps();
          if (maps != null) {
            String title = maps.getTitle();  // for example, "Heaven on 7th Marketplace"
            String uri = maps.getUri();  // for example, "https://maps.google.com/?cid=13100894621228039586"
            String placeId = maps.getPlaceId();  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
            // TODO(developer): show sources in the UI
          }
        }
      }
    }
  }

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

Web

// ...

// Get the model's text response
const text = result.response.text();

// Get the grounding metadata
const groundingMetadata = result.response.candidates?.[0]?.groundingMetadata;

// Get sources
const groundingChunks = groundingMetadata?.groundingChunks;
if (groundingChunks) {
  for (const chunk of groundingChunks) {
    const title = chunk.maps?.title;  // for example, "Heaven on 7th Marketplace"
    const uri = chunk.maps?.uri;  // for example, "https://maps.google.com/?cid=13100894621228039586"
    const placeId = chunk.maps?.placeId;  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
    // TODO(developer): show sources in the UI
  }
}

Dart

// ...

// Get the model's response
final text = response.text;

// Get the grounding metadata
final groundingMetadata = response.candidates.first.groundingMetadata;

// Get sources
final groundingChunks = groundingMetadata?.groundingChunks;
if (groundingChunks != null) {
  for (var chunk in groundingChunks) {
    final title = chunk.maps?.title;  // for example, "Heaven on 7th Marketplace"
    final uri = chunk.maps?.uri;  // for example, "https://maps.google.com/?cid=13100894621228039586"
    final placeId = chunk.maps?.placeId;  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
    // TODO(developer): show sources in the UI
  }
}

Unity

// ...

// Get the model's response.
var text = response.Text;

// Get the grounding metadata.
var groundingMetadata = response.Candidates.First().GroundingMetadata;

// Get sources.
if (groundingMetadata != null) {
  foreach(GroundingChunk chunk in groundingMetadata?.GroundingChunks) {
    if (chunk.Maps != null) {
      var title = chunk.Maps?.Title;  // for example, "Heaven on 7th Marketplace"
      var uri = chunk.Maps?.Uri;  // for example, "https://maps.google.com/?cid=13100894621228039586"
      var placeId = chunk.Maps?.PlaceId;  // for example, "places/ChIJ0-zA1vBZwokRon0fGj-6z7U"
      // TODO(developer): show sources in the UI
    }
  }
}

對於 groundingChunks 中的每個來源,必須按照下列規定產生連結預覽:

提示詞和回覆,並顯示來源

您可以收合來源檢視畫面。

提示詞與回覆和來源 (收合)

您也可以視需要加入其他內容,強化連結預覽畫面,例如:

如要進一步瞭解部分 Google Maps 資料供應商及其授權條款,請參閱 Google 地圖和 Google 地球法律聲明。

Google Maps 項文字出處規範

在文字中註明來源為 Google Maps 時,請遵循下列規範:

  • 請勿以任何方式修改文字 Google Maps:

    • 請勿變更文字 Google Maps 的大小寫。
    • 請勿將文字 Google Maps 換行。
    • 請勿將文字 Google Maps 本地化為其他語言。
    • 使用 HTML 屬性 translate="no",防止瀏覽器翻譯文字 Google Maps。
  • 按照下表所述設定文字 Google Maps 的樣式:

    屬性 樣式
    字型系列 Roboto。載入字型為選用步驟。
    備用字型系列 產品中已使用的任何 Sans Serif 內文字型,或「Sans-Serif」以叫用預設系統字型
    字型樣式 正常
    字型粗細 400
    字型顏色 白色、黑色 (#1F1F1F) 或灰色 (#5E5E5E)。 與背景保持無障礙 (4.5:1) 對比度。
    字型大小 字型大小下限:12sp
    字型大小上限:16sp
    如要瞭解 sp,請參閱 Material Design 網站上的字型大小單位。
    間距 正常

CSS 範例

下列 CSS 會以適當的字體樣式和顏色,在白色或淺色背景上顯示「Google Maps」文字。

@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

.GMP-attribution {
  font-family: Roboto, Sans-Serif;
  font-style: normal;
  font-weight: 400;
  font-size: 1rem;
  letter-spacing: normal;
  white-space: nowrap;
  color: #5e5e5e;
}

快取地點 ID

Google Maps Grounded Result 可能包含地點 ID。您可以快取、儲存及匯出下列回應資料:

  • placeId

《利用 Google 地圖建立基準服務條款》中對快取的限制不適用於這類資料。

禁止的活動和地域

為維護安全可靠的平台,使用 Google Maps 建立基準時,特定內容和活動會受到額外限制。除了所選 Gemini API 供應商條款中的使用限制外:Gemini Developer API 或 Agent Platform Gemini API (formerly Vertex AI) (請參閱「服務專屬條款」中的「服務條款」一節)。

  • 您不會將 Grounding with Google Maps 用於高風險活動,包括緊急應變服務。

  • 您不會在禁止區域發布或行銷提供 Google Maps 基準化服務的應用程式。詳情請參閱「Google Maps Platform 禁止地區」一文。「禁止地域」清單可能會不時更新。

Firebase 控制台中的基準化結果和 AI 監控

如果您已在 Firebase 控制台啟用 AI monitoring,回覆會儲存在 Cloud Logging。根據預設,這類資料的保留期限為 30 天。

您有責任確保這個保留期限或您設定的任何自訂期限,完全符合您的特定用途,以及所選 Gemini API 供應商的任何其他法規遵循要求:Gemini Developer API或 Agent Platform Gemini API (formerly Vertex AI) (請參閱《服務專屬條款》中的「服務條款」一節)。您可能需要在 Cloud Logging 中調整保留期限,才能符合這些規定。

定價和頻率限制

使用 Google Maps 建立基準的費用是依查詢計費。只有在提示成功傳回至少一個Google Maps基準結果 (即回覆包含至少一個Google Maps來源) 時,要求才會計入Google Maps配額。如果單一要求向 Google Maps 傳送多個查詢,系統會將其視為一個要求,計入頻率限制。

請務必查看所選 Gemini API 供應商說明文件,瞭解使用 Google Maps 建立基準的定價、模型可用性和限制:Gemini Developer API | Agent Platform Gemini API (formerly Vertex AI)。