Dynamic Library Import API 是一種新的解決方案,用於載入 Maps JavaScript API 和隨附的所有程式庫。藉助在執行階段動態載入程式庫這項功能,您不必擔心跨元件依附元件的問題,且能以 promise 為基礎載入程式庫。此外,使用 Maps JavaScript API 時,該功能還可讓您避免使用長命名空間 (但系統仍會填入長命名空間,且仍可使用)。
使用動態匯入程式庫
如要使用 Dynamic Library Import API,請在 HTML 頁面中加入內嵌 Bootstrap 載入器的指令碼標記,以及呼叫 importLibrary()
的執行階段程式碼 (您也可以使用簡易指令碼載入器執行此動作;在這種情況下,應用程式程式碼必須等待回呼才能使用 importLibrary
)。請複製下列程式碼,並新增 API 金鑰及應用程式所需的任何 Bootstrap 參數:
<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_HERE",
v: "beta",
// Add other bootstrap parameters as needed, using camel case.
});
</script>
如要在執行階段載入程式庫,請使用 await
運算子從非同步函式中呼叫 importLibrary()
,如下所示:
let map;
async function initMap() {
// Create the map.
const { Map, InfoWindow } = await google.maps.importLibrary("maps");
map = new Map(document.getElementById("map"),{
center: { lat: 37.4239163, lng: -122.0947209 },
zoom: 14,
mapId: 'DEMO_MAP_ID',
});
// Add an info window.
const infoWindow = new InfoWindow({
ariaLabel: "Googleplex",
});
// Add a marker.
const {AdvancedMarkerView} = await google.maps.importLibrary("marker");
const markerView = new AdvancedMarkerView({
map,
position: { lat: 37.4239163, lng: -122.0947209 },
title: 'Googleplex, Mountain View CA'
});
markerView.addListener('click', () => {
infoWindow.close();
infoWindow.setContent('<b>Googleplex</b>, Mountain View CA');
infoWindow.open(markerView.map, markerView);
});
}
initMap();
必要參數
自選參數
libraries
:逗號分隔的清單,包含要載入的其他 Maps JavaScript API 程式庫。我們通常不建議指定一組固定的程式庫,開發人員如想微調網站的快取行為,則可以這麼做。但請注意,如果系統需要未指定的程式庫,這項操作可能會導致載入速度變慢。language
:要使用的語言。這會影響控制項名稱、版權聲明、行車路線和控制項標籤,以及對服務要求的回應。查看支援語言清單。region
:要使用的區碼。這會根據特定國家/地區或地域調整地圖行為。solutionChannel
:Google 地圖平台提供多種程式碼範例,有助您快速完成設定並開始使用。為追蹤複雜程式碼範例的採用情況,以及改善解決方案品質,Google 會在程式碼範例的 API 呼叫中加入solution_channel
查詢參數。authReferrerPolicy
:Maps JS 客戶可在 Cloud 控制台中設定 HTTP 參照網址限制,以限制哪些網址可使用特定 API 金鑰。根據預設,您可以將這些限制設為僅允許特定路徑使用 API 金鑰。如果相同網域或來源的任何網址可能會使用 API 金鑰,您就可以設定authReferrerPolicy: "origin"
,限制在授權 Maps JavaScript API 要求時傳送的資料量。如果指定這個參數,且在 Cloud 控制台中已啟用 HTTP 參照網址限制,則只有在 HTTP 參照網址限制與目前網站網域相符 (未指定路徑) 時,才能載入 Maps JavaScript API。