向地图添加标记

请选择平台: 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',
});

如果您使用的是 Web 组件,则可以直接在 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);
}

只有在使用 Web 组件时才能附加元素。如果使用 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;

查看完整的示例源代码

此示例展示了如何向地图添加标记。

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>

试用选段

后续步骤