您可以使用標記在地圖上顯示單一位置。本頁說明如何使用程式輔助方式和自訂 HTML 元素,在地圖中新增標記。
載入進階標記庫
地圖程式碼必須載入 marker 程式庫,才能在地圖中新增進階標記。這個程式庫提供 AdvancedMarkerElement 和 PinElement 類別。無論應用程式使用程式輔助方式或 HTML 載入標記,這一點都適用。為此,應用程式必須先載入 Maps JavaScript API。
標記庫載入方法取決於網頁載入 Maps JavaScript API 的方式。
如果您的網頁使用動態指令碼載入,請在執行階段新增標記庫並匯入
AdvancedMarkerElement(選用項目:PinElement),如下所示。const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
如果您的網頁使用直接指令碼載入標記,請在載入指令碼中新增
libraries=marker,如下列程式碼片段所示。這樣做會導致系統匯入AdvancedMarkerElement和PinElement。<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&libraries=marker" defer ></script>
設定地圖 ID
如要使用進階標記,則必須提供地圖 ID (可使用 DEMO_MAP_ID)。在地圖選項中設定地圖 ID,如下所示:
const map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: 37.4239163, lng: -122.0947209 }, zoom: 14, mapId: 'DEMO_MAP_ID', });
進一步瞭解地圖 ID。
使用自訂 HTML 元素新增標記
如要使用自訂 HTML 元素新增進階標記,請在 gmp-map 元素中加入 gmp-advanced-marker 子項元素。下列程式碼片段顯示如何在網頁上新增標記:
<gmp-map
center="43.4142989,-124.2301242"
zoom="4"
map-id="DEMO_MAP_ID"
style="height: 400px"
>
<gmp-advanced-marker
position="37.4220656,-122.0840897"
title="Mountain View, CA"
></gmp-advanced-marker>
<gmp-advanced-marker
position="47.648994,-122.3503845"
title="Seattle, WA"
></gmp-advanced-marker>
</gmp-map>查看完整範例原始碼
這個範例說明如何使用 HTML 建立含有標記的地圖。
TypeScript
// This example adds a map with markers, using web components. async function initMap(): Promise<void> { console.log('Maps JavaScript API loaded.'); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// This example adds a map with markers, using web components. async function initMap() { console.log("Maps JavaScript API loaded."); } window.initMap = 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; } gmp-map { height: 400px; }
HTML
<html>
<head>
<title>Add a Map with Markers using HTML</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<gmp-map
center="43.4142989,-124.2301242"
zoom="4"
map-id="DEMO_MAP_ID"
style="height: 400px"
>
<gmp-advanced-marker
position="37.4220656,-122.0840897"
title="Mountain View, CA"
></gmp-advanced-marker>
<gmp-advanced-marker
position="47.648994,-122.3503845"
title="Seattle, WA"
></gmp-advanced-marker>
</gmp-map>
<!--
The `defer` attribute causes the script to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises. See
https://developers.google.com/maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=maps,marker&v=beta"
defer
></script>
</body>
</html>測試範例
使用程式輔助方式新增標記
如要使用程式輔助方式在地圖中新增進階標記,請建立新的 AdvancedMarkerElement,並傳遞 LatLng 或 LatLngAltitude 及基本地圖的參照,如下例所示:
const marker = new AdvancedMarkerElement({
map,
position: { lat: 37.4239163, lng: -122.0947209 },
});
如要從地圖中移除標記,請將 markerView.map 或 position 設為 null。
查看完整範例原始碼
本例說明如何在 Google 地圖中加入標記。
TypeScript
async function initMap() { // Request needed libraries. const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; const map = new Map(document.getElementById('map') as HTMLElement, { center: { lat: 37.4239163, lng: -122.0947209 }, zoom: 14, mapId: '4504f8b37365c3d0', }); const marker = new AdvancedMarkerElement({ map, position: { lat: 37.4239163, lng: -122.0947209 }, }); } initMap();
JavaScript
async function initMap() { // Request needed libraries. const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); const map = new Map(document.getElementById('map'), { center: { lat: 37.4239163, lng: -122.0947209 }, zoom: 14, mapId: '4504f8b37365c3d0', }); const marker = new AdvancedMarkerElement({ map, position: { lat: 37.4239163, lng: -122.0947209 }, }); } 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>Default Advanced Marker</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!-- 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>
</html>