您可以使用 HTML、CSS 和 JavaScript 程式碼,在網頁中新增 Google 地圖。本頁說明如何在網頁中新增地圖,然後以程式輔助方式存取地圖執行個體。
總覽
如要載入地圖,網頁必須完成下列操作:
- 使用 Bootstrap 載入器載入 Maps JavaScript API。API 金鑰會在此處傳遞。這個載入器可新增至 HTML 或 JavaScript 來源檔案。
- 在 HTML 網頁中新增地圖,並加入所需的 CSS 樣式。
- 載入
maps程式庫並初始化地圖。
使用 gmp-map 元素新增地圖
建議使用 gmp-map 元素在網頁中新增 Google 地圖。這是使用網頁元件建立的自訂 HTML 元素。如要使用 gmp-map 元素在網頁中新增地圖,請按照下列步驟操作。
將包含 Bootstrap 的
script元素新增至 HTML 網頁,或將其新增至 JavaScript 或 TypeScript 來源檔案,但不要使用script元素。使用 API 金鑰和任何其他選項設定 Bootstrap。您可以選擇動態匯入程式庫或直接載入指令碼。這個範例說明如何在 HTML 網頁中新增動態指令碼載入啟動程序:<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>
在 HTML 網頁上,新增
gmp-map元素。指定center的經緯度座標 (必要)、zoom的縮放等級 (必要),以及視需要指定map-id(部分功能需要此屬性,例如進階標記)。
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
完整程式碼範例
TypeScript
async function initMap(): Promise<void> { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
JavaScript
async function initMap() { // Import the needed libraries. await google.maps.importLibrary('maps'); // Create the map. const mapElement = document.querySelector('gmp-map'); // Access the underlying map object. const innerMap = mapElement.innerMap; } initMap();
CSS
/* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- prettier-ignore -->
<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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</head>
<body>
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>
</body>
</html>試用範例
使用 div 元素和 JavaScript 新增地圖
如要使用 div 元素在網頁中新增地圖,請按照下列步驟操作。
將包含 Bootstrap 的
script元素新增至 HTML 網頁,或將其新增至 JavaScript 或 TypeScript 來源檔案,但不要使用script元素。使用 API 金鑰和任何其他選項設定 Bootstrap。您可以選擇動態匯入程式庫或直接載入指令碼。這個範例說明如何將動態啟動程序新增至 HTML 網頁:<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>
在 HTML 網頁上,新增
div元素來包含地圖。<div id="map"></div>
在 CSS 中,將地圖高度設為 100%。地圖必須有 CSS
height屬性才能顯示。#map { height: 100%; }
在 JS 或 TS 檔案中,建立函式來載入
maps程式庫,並初始化地圖。指定center的經緯度座標,以及zoom的縮放等級。視需要使用mapId屬性新增地圖 ID。地圖預設為光柵地圖,因此請指定「VECTOR」地圖選項來要求向量地圖。建議使用向量地圖類型,因為這類地圖的視覺保真度較高,且可控制地圖的傾斜度和方向,提供最佳使用者體驗。TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
查看完整原始碼範例
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary( 'maps' )) as google.maps.MapsLibrary; // Create a new map from the div with id="map". map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
JavaScript
let map; async function initMap() { // Import the needed libraries const { Map, RenderingType } = (await google.maps.importLibrary('maps')); // Create a new map from the div with id="map". map = new Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, renderingType: "VECTOR", }); } initMap();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Simple Map</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
<!-- prettier-ignore -->
<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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly" });</script>
</body>
</head>
<body>
<div id="map"></div>
</body>
</html>試用範例
在地圖執行個體上設定及取得屬性
如要與地圖例項互動,請選取包含元素。視您使用 gmp-map 元素或 div 元素而定,執行這項操作的程式碼會有所不同。
從 gmp-map 元素取得地圖例項
使用 gmp-map 元素時,如要取得地圖例項,請使用 document.querySelector 擷取 mapElement 例項,如下所示。
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
然後設定 mapElement 執行個體的屬性:
mapElement.zoom = 8;
MapElement 類別會在內部使用 Map 類別;請使用 MapElement.innerMap 屬性存取 Map 類別,如下所示:
mapElement.innerMap.setOptions({
mapTypeControl: false,
});
從 div 元素取得地圖例項
使用 div 元素時,請在初始化時取得地圖例項並設定選項:
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
初始化後,請在 map 執行個體上設定選項,如下所示:
map.setOptions({
zoom: 8,
});