開始使用

本頁說明如何取得 API 金鑰、啟用必要的 API,並載入 Places Library,接著才能使用「地點」類別。

取得 API 金鑰並啟用必要的 API

使用「地點」類別前,請務必:

  • 使用帳單帳戶建立 Cloud 專案。
  • 取得 API 金鑰。
  • 啟用下列 API:
    • Maps JavaScript API
    • Places API
    • Places API (新版) - 如要使用 Text Search (新版)、Nearby Search (新版)、Place Details (新版),則必須啟用此 API

詳情請參閱「設定 Google Cloud 專案」一文。

取得 API 金鑰

啟用 Places API (新版)

載入 Places Library

如要載入 Places Library,請先將內嵌 Bootstrap 載入器加進應用程式程式碼,載入 Maps JavaScript API,如以下程式碼片段所示:

<script>
  (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
    key: "YOUR_API_KEY",
    v: "weekly",
    // Use the 'v' parameter to indicate the version to use (weekly, beta, alpha, etc.).
    // Add other bootstrap parameters as needed, using camel case.
  });
</script>

接下來,請使用 await 運算子,從 async 函式內呼叫 importLibrary(),如下所示:

  const {Place} = await google.maps.importLibrary("places");
  

後續步驟