Google マップをウェブページに追加する

HTML、CSS、JavaScript コードを使用して、Google マップをウェブページに追加できます。 このページでは、地図をウェブページに追加し、プログラムで地図インスタンスにアクセスする方法について説明します。

概要

地図を読み込むには、ウェブページで次のことを行う必要があります。

  • Maps JavaScript API を ブートストラップ ローダを使用して読み込む。ここで API キーが渡され、HTML または JavaScript のソースファイルに追加されます。
  • 地図を HTML ページに追加し、必要な CSS スタイルを追加する。
  • maps ライブラリを読み込み、地図を初期化する。

gmp-map 要素を使って地図を追加する

gmp-map 要素は、Google マップをウェブページに追加する場合に推奨される方法です。これは、ウェブ コンポーネントを使用して作成されるカスタム HTML 要素です。gmp-map 要素を使用して地図をウェブページに追加する手順は次のとおりです。

  1. ブートストラップを含む script 要素を HTML ページに追加するか、script 要素なしで JavaScript または TypeScript のソースファイルに追加します。 API キーとその他のオプションでブートストラップを構成します。動的ライブラリのインポートまたは直接スクリプトの読み込みを選択できます。この例では、動的スクリプトの読み込みブートストラップを 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>

    詳しくは、Google Maps JavaScript API の読み込みについての記事をご覧ください。

  2. 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 要素を使用して地図をウェブページに追加する手順は次のとおりです。

  1. ブートストラップを含む script 要素を HTML ページに追加するか、script 要素なしで JavaScript または TypeScript のソースファイルに追加します。 API キーとその他のオプションでブートストラップを構成します。動的ライブラリのインポートまたは直接スクリプトの読み込みを選択できます。この例では、動的ブートストラップを 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>

    詳しくは、Google Maps JavaScript API の読み込みについての記事をご覧ください。

  2. HTML ページで、div 要素を追加して、地図を含めます。

    <div id="map"></div>
  3. CSS で地図の高さを 100% に設定します。地図を表示するには、CSS の height 属性が必要です。

    #map {
      height: 100%;
    }
  4. 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,
});