マップにマーカーを追加する

プラットフォームを選択: Android iOS JavaScript

各マーカーを使って地図上に場所を表示します。このページでは、プログラマティックにマーカーを地図に追加する方法と、カスタム HTML 要素を使用してマーカーを地図に追加する方法を説明します。

高度なマーカー ライブラリを読み込む

地図に高度なマーカーを追加するには、AdvancedMarkerElementPinElement を提供する marker ライブラリを、地図のコードで読み込む必要があります。これは、アプリでマーカーをプログラマティックに読み込む場合も、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-advanced-marker 子要素を gmp-map 要素に追加します。ウェブページにマーカーを追加するスニペットは次のとおりです。

<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.map または marker.positionnull に設定します。

// 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>

サンプルを試す

次のステップ