Dynamic Library Import API 是一种新的方式,用于加载 Maps JavaScript API 及其附带的所有库。借助在运行时动态加载库这一功能,您无需操心跨组件依赖项,同时可以基于 promise 加载库。此外,在使用 Maps JavaScript API 时,该功能还可让您避免使用长命名空间(长命名空间仍会填充且仍可使用)。
使用 Dynamic Library Import
若要使用 Dynamic Library Import API,请将内嵌引导程序加载器的脚本标记添加到您的 HTML 网页,然后添加运行时代码,以调用 importLibrary()
(您也可以使用简单的脚本加载器来执行此操作;在这种情况下,您的应用代码必须先等待回调,然后再使用 importLibrary
)。请复制以下代码,并添加您的 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_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 Maps Platform 提供了许多类型的示例代码,可帮助您快速上手。为了跟踪更复杂的代码示例的采用情况并提高解决方案质量,Google 在示例代码的 API 调用中添加了solution_channel
查询参数。authReferrerPolicy
:Maps JS 客户可以在 Cloud 控制台中配置 HTTP 引荐来源网址限制,以限制哪些网址可以使用特定的 API 密钥。默认情况下,这类限制可以配置为仅允许某些路径使用某个 API 密钥。如果同一网域或同一来源的任何网址都可以使用该 API 密钥,您可以在授权来自 Maps JavaScript API 的请求时设置authReferrerPolicy: "origin"
,以限制发送的数据量。如果指定了此参数并且在 Cloud 控制台中启用了 HTTP 引荐来源网址限制,则只有在 HTTP 引荐来源网址限制与当前网站的网域(未指定路径)匹配的情况下,Maps JavaScript API 才会加载。