在地圖上新增標記

選取平台: Android iOS JavaScript

您可以使用標記在地圖上顯示單一位置。本頁說明如何使用程式輔助方式和自訂 HTML 元素,在地圖中新增標記。

載入進階標記庫

地圖程式碼必須載入 marker 程式庫,才能在地圖中新增進階標記。這個程式庫提供 AdvancedMarkerElementPinElement 類別。無論應用程式使用程式輔助方式或 HTML 載入標記,這一點都適用。為此,應用程式必須先載入 Maps JavaScript API

標記庫載入方法取決於網頁載入 Maps JavaScript API 的方式。

  • 如果您的網頁使用動態指令碼載入,請在執行階段新增標記庫並匯入 AdvancedMarkerElement (選用項目:PinElement),如下所示。

    const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
  • 如果您的網頁使用直接指令碼載入標記,請在載入指令碼中新增 libraries=marker,如下列程式碼片段所示。這樣做會導致系統匯入 AdvancedMarkerElementPinElement

    <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',
});

如果您使用網頁元件,可以直接在 gmp-map 元素上設定地圖 ID:

<gmp-map center="37.4239163,-122.0947209" zoom="14" map-id="DEMO_MAP_ID"></gmp-map>

進一步瞭解地圖 ID

使用自訂 HTML 元素新增標記

如要使用自訂 HTML 元素新增進階標記,請在 gmp-map 元素中加入 gmp-advanced-marker 子項元素。下列程式碼片段顯示如何在網頁上新增標記:

<gmp-map
    center="41.027748173921374, -92.41852445367961"
    zoom="13"
    map-id="DEMO_MAP_ID">
    <gmp-advanced-marker
        position="41.027748173921374, -92.41852445367961"
        title="Ottumwa, IA"></gmp-advanced-marker>
</gmp-map>

查看完整範例原始碼

這個範例說明如何使用 HTML 建立含有標記的地圖。

TypeScript

// This example adds a map with markers, using web components.
async function initMap() {
    console.log('Maps JavaScript API loaded.');
}
initMap();

JavaScript

// This example adds a map with markers, using web components.
async function initMap() {
    console.log('Maps JavaScript API loaded.');
}
initMap();

CSS

/* Note: This CSS file is intentionally blank. */

HTML

<html>
    <head>
        <title>Add a Map with Markers using HTML</title>
        <style>
            gmp-map {
                height: 100%;
            }
            html,
            body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
        </style>
        <script type="module" src="./index.js"></script>
        <script
            src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&libraries=maps,marker&v=weekly&internal_usage_attribution_ids=gmp_git_jsapisamples_v1_web-components"
            defer></script>
    </head>
    <body>
        <gmp-map
            center="41.027748173921374, -92.41852445367961"
            zoom="13"
            map-id="DEMO_MAP_ID">
            <gmp-advanced-marker
                position="41.027748173921374, -92.41852445367961"
                title="Ottumwa, IA"></gmp-advanced-marker>
        </gmp-map>
    </body>
</html>

試用範例

使用程式輔助方式新增標記

如要使用程式輔助方式在地圖中新增進階標記,請建立新的 AdvancedMarkerElement,然後附加至地圖,如下例所示:

TypeScript

const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;

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 marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}

JavaScript

const mapElement = document.querySelector('gmp-map');
async function initMap() {
    // Request needed libraries.
    const { Map } = (await google.maps.importLibrary('maps'));
    const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker'));
    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}

使用網頁元件時,才能附加元素。如果使用 div 元素載入地圖,請使用 map 屬性將標記與地圖執行個體建立關聯,如下所示:

myMap = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
});

const marker = new AdvancedMarkerElement({
    map: myMap,
    position: { lat: -34.397, lng: 150.644 },
});

移除標記

如要從地圖中移除標記,請將 marker.mapmarker.position 設為 null

// Set the map to null.
marker.map = null;

// Set the position to null.
marker.position = null;

查看完整範例原始碼

本例說明如何在 Google 地圖中加入標記。

TypeScript

const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;

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 marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}
initMap();

JavaScript

const mapElement = document.querySelector('gmp-map');
async function initMap() {
    // Request needed libraries.
    const { Map } = (await google.maps.importLibrary('maps'));
    const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker'));
    const marker = new AdvancedMarkerElement({
        position: { lat: 37.4239163, lng: -122.0947209 },
    });
    mapElement.append(marker);
}
initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
gmp-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>
        <!-- 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="37.4239163,-122.0947209"
            zoom="14"
            map-id="4504f8b37365c3d0"></gmp-map>
    </body>
</html>

試用範例

後續步驟