マーカーが配置された Google マップをウェブサイトに追加する

はじめに

このチュートリアルでは、マーカーが配置されたシンプルな Google マップをウェブページに追加する方法を説明します。HTML と CSS について初級から中級の知識があり、JavaScript についても若干の知識がある方に適しています。地図の作成に関する高度なガイドについては、デベロッパー ガイドをご覧ください。

このチュートリアルで作成する地図は次のとおりです。マーカーは、ウルル・カタ・ジュタ国立公園のウルル(エアーズロックとも呼ばれます)にあります。


TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

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>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

サンプルを試す

ご利用にあたって

マーカーが配置された Google マップをウェブページ上に作成する際は、次の 3 つのステップに従います。

  1. HTML ページを作成する
  2. マーカー付きの地図を追加する
  3. API キーを取得する

この作業には、ウェブブラウザが必要です。使用するプラットフォームに応じて、対応しているブラウザのリストから、Google Chrome(推奨)、Firefox、Safari、Edge などのよく知られたブラウザを選択します。

ステップ 1: HTML ページを作成する

基本的な HTML ウェブページのコードを次に示します。

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "beta"});</script>
  </body>
</html>

これは、見出しレベル 3(h3)と単一の div 要素で構成されるごく基本的なページです。ウェブページには任意のコンテンツを追加することができます。

コードについて

以下のコードで、head と body で構成される HTML ページを作成します。

<html>
 <head>
 </head>
 <body>
 </body>
</html>

以下のコードを使用すると、地図上部に見出しレベル 3 を追加できます。

<h3>My Google Maps Demo</h3>

以下のコードでは、Google マップのページ領域を定義します。

<!--The div element for the map -->
<div id="map"></div>

チュートリアルのこの段階では、地図がまだ追加されていないため、div はグレーブロックとして表示されます。以下のコードは、div のサイズと色を設定する CSS を記述しています。

/* Set the size of the div element that contains the map */
#map {
    height: 400px; /* The height is 400 pixels */
    width: 100%; /* The width is the width of the web page */
}

上記のコードでは、style 要素で地図の div サイズを設定しています。地図を表示するには、div の幅と高さを 0 ピクセルより大きい値に設定してください。この例では、div の高さが 400 ピクセル、幅が 100% に設定されており、ウェブページの幅いっぱいに表示されます。

ブートストラップ ローダーにより、Maps JavaScript API の読み込みが準備されます(importLibrary() が呼び出されるまでライブラリは読み込まれません)。

<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_HERE",
    // Add other bootstrap parameters as needed, using camel case.
    // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
  });
</script>

独自の API キーを取得する方法については、ステップ 3: API キーを取得するをご覧ください。

ステップ 2: マーカーが配置された地図を追加する

このセクションでは、Maps JavaScript API をウェブページに読み込む方法と、この API を使用してマーカーが配置された地図を追加する独自の JavaScript を記述する方法について説明します。

TypeScript

// Initialize and add the map
let map;
async function initMap(): Promise<void> {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };

  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

  // The map, centered at Uluru
  map = new Map(
    document.getElementById('map') as HTMLElement,
    {
      zoom: 4,
      center: position,
      mapId: 'DEMO_MAP_ID',
    }
  );

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: 'Uluru'
  });
}

initMap();

JavaScript

// Initialize and add the map
let map;

async function initMap() {
  // The location of Uluru
  const position = { lat: -25.344, lng: 131.031 };
  // Request needed libraries.
  //@ts-ignore
  const { Map } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

  // The map, centered at Uluru
  map = new Map(document.getElementById("map"), {
    zoom: 4,
    center: position,
    mapId: "DEMO_MAP_ID",
  });

  // The marker, positioned at Uluru
  const marker = new AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

上記のコードでは、initMap() 関数が呼び出されると、Map ライブラリと AdvancedMarkerView ライブラリが読み込まれます。

コードについて

以下のコードでは、新しい Google マップ オブジェクトが作成され、中心とズームレベルを含むプロパティが地図に追加されます。その他のプロパティ オプションについては、ドキュメントをご覧ください。

TypeScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };

// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;
const { AdvancedMarkerView } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;

// The map, centered at Uluru
map = new Map(
  document.getElementById('map') as HTMLElement,
  {
    zoom: 4,
    center: position,
    mapId: 'DEMO_MAP_ID',
  }
);

JavaScript

// The location of Uluru
const position = { lat: -25.344, lng: 131.031 };
// Request needed libraries.
//@ts-ignore
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerView } = await google.maps.importLibrary("marker");

// The map, centered at Uluru
map = new Map(document.getElementById("map"), {
  zoom: 4,
  center: position,
  mapId: "DEMO_MAP_ID",
});

上記のコードでは、new Map() によって新しい Google マップ オブジェクトが作成されます。center プロパティは、地図の中心位置を API に指示します。

詳しくは、緯度と経度の座標を取得する方法、または住所を地理座標に変換する方法をご覧ください。

zoom プロパティでは、地図のズームレベルを指定します。0 は最小ズームレベルで、Earth 全体を表示します。より高解像度で Earth にズームインするには、ズームレベルにより大きい値を設定します。

以下のコードで、地図上にマーカーを配置します。position プロパティは、マーカーの位置を設定します。

TypeScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerView({
  map: map,
  position: position,
  title: 'Uluru'
});

JavaScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerView({
  map: map,
  position: position,
  title: "Uluru",
});

マーカーについて詳しくは、次の記事をご覧ください。

ステップ 3: API キーを取得する

このセクションでは、独自の API キーを使用して、Maps JavaScript API に対してアプリを認証する方法について説明します。

次のステップに従って、API キーを取得します。

  1. Google Cloud Console に移動します。

  2. プロジェクトを作成または選択します。

  3. [続行] をクリックして、API と関連サービスを有効にします。

  4. [認証情報] ページで API キーを取得します(API キーの制限も設定します)。制限のない既存の API キーまたはブラウザの制限が設定されたキーがある場合は、そのキーを使用することもできます。

  5. 割り当ての盗用を防ぎ、API キーを保護する方法については、API キーの使用をご覧ください。

  6. 課金を有効化します。詳細については、使用量と課金をご覧ください。

  7. このチュートリアルのページにあるコード全体をテキスト エディタにコピーします。

  8. URL の key パラメータの値を、実際の API キー(上記のステップで取得した API キー)に置き換えます。

    <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_HERE",
        // Add other bootstrap parameters as needed, using camel case.
        // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
      });
    </script>
    
  9. このファイルは、.html で終わる名前(index.html など)で保存します。

  10. HTML ファイルをパソコンからウェブブラウザにドラッグして、ブラウザで読み込みます。ほとんどのオペレーティング システムでは、HTML ファイルをダブルクリックしても同じ操作が可能です。

ヒントとトラブルシューティング

  • スタイルやプロパティなどのオプションを微調整して、地図をカスタマイズできます。地図のカスタマイズについて詳しくは、スタイル地図上への図形描画に関するガイドをご覧ください。
  • ウェブブラウザでデベロッパー ツール コンソールを使用すると、コードをテストして実行したり、エラーレポートを確認したり、コードの問題を解決したりできます。
  • Chrome でコンソールを開くには、キーボード ショートカットを使用します。
    Mac の場合は Command+Option+J キー、Windows の場合は Ctrl+Shift+J キーです。
  • Google マップ上のビジネス拠点の緯度と経度の座標を取得する手順は次のとおりです。

    1. ブラウザで Google マップを開きます。
    2. 地図上で、座標が必要な場所の正確な位置を右クリックします。
    3. 表示されるコンテキスト メニューから [この場所について] を選択します。地図画面の下部にカードが表示されます。カードの最後の行で緯度と経度の座標を確認します。
  • ジオコーディング サービスを使用すると、住所を緯度と経度の座標に変換できます。デベロッパー ガイドで、ジオコーディング サービスの利用方法について詳しく説明しています。