はじめに
このチュートリアルでは、マーカーが配置されたシンプルな Google マップをウェブページに追加する方法を説明します。HTML と CSS について初級から中級の知識があり、JavaScript についても若干の知識がある方に適しています。地図の作成に関する高度なガイドについては、デベロッパー ガイドをご覧ください。
このチュートリアルで作成する地図は次のとおりです。マーカーは、ウルル・カタ・ジュタ国立公園のウルル(エアーズロックとも呼ばれます)にあります。
以下のセクションに、このチュートリアルで地図を作成するために必要なコード全体を載せています。
TypeScript
// Initialize and add the map function initMap(): void { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 4, center: uluru, } ); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } window.initMap = initMap;
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 */ }
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> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises with https://www.npmjs.com/package/@googlemaps/js-api-loader. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body> </html>
サンプルを試す
始める
マーカーが配置された Google マップをウェブページ上に作成する際は、次の 3 つのステップに従います。
この作業には、ウェブブラウザが必要です。使用するプラットフォームに応じて、対応しているブラウザのリストから、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> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises with https://www.npmjs.com/package/@googlemaps/js-api-loader. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></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 を記述しています。
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ /* 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% に設定されており、ウェブページの幅いっぱいに表示されます。
ステップ 2: マーカーが配置された地図を追加する
このセクションでは、Maps JavaScript API をウェブページに読み込む方法と、この API を使用してマーカーが配置された地図を追加する独自の JavaScript を記述する方法について説明します。
TypeScript
// Initialize and add the map function initMap(): void { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 4, center: uluru, } ); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } declare global { interface Window { initMap: () => void; } } window.initMap = initMap;
JavaScript
// Initialize and add the map function initMap() { // The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, }); // The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, }); } window.initMap = initMap;
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 */ }
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> <!-- The `defer` attribute causes the callback to execute after the full HTML document has been parsed. For non-blocking uses, avoiding race conditions, and consistent behavior across browsers, consider loading using Promises with https://www.npmjs.com/package/@googlemaps/js-api-loader. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly" defer ></script> </body> </html>
サンプルを試す
コードについて
以下のコードでは、script
によって、指定された URL から API を読み込みます。
<script async
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
上記のコードでは、callback
パラメータによって、API の読み込み後に initMap
関数が実行されます。async
属性によって、ブラウザで、API の読み込み中もページの他の部分の解析を続行できます。読み込みが完了すると、ブラウザはスクリプトを一時停止してすぐに実行します。key
パラメータには API キーが含まれます。
独自の API キーを取得する方法については、後述のステップ 3: API キーを取得するをご覧ください。
以下のコードには、ウェブページの読み込み時に地図を初期化して追加する initMap
関数が含まれています。script
タグを使用して、initMap
関数を含む独自の JavaScript を組み込みます。
function initMap() {}
document.getElementById()
関数を追加して、ウェブページ上の地図の div
を見つけます。
以下のコードでは、新しい Google マップ オブジェクトが作成され、中心とズームレベルを含むプロパティが地図に追加されます。その他のプロパティ オプションについては、ドキュメントをご覧ください。
TypeScript
// The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map( document.getElementById("map") as HTMLElement, { zoom: 4, center: uluru, } );
JavaScript
// The location of Uluru const uluru = { lat: -25.344, lng: 131.031 }; // The map, centered at Uluru const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: uluru, });
上記のコードでは、new google.maps.Map()
によって新しい Google マップ オブジェクトが作成されます。center
プロパティは、地図の中心位置を API に指示します。
詳しくは、緯度と経度の座標を取得する方法、または住所を地理座標に変換する方法をご覧ください。
zoom
プロパティでは、地図のズームレベルを指定します。0 は最小ズームレベルで、地球全体を表示します。より高解像度で地球にズームインするには、ズームレベルにより大きい値を設定します。
以下のコードでは、地図上にマーカーを配置します。position
プロパティは、マーカーの位置を設定します。
TypeScript
// The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, });
JavaScript
// The marker, positioned at Uluru const marker = new google.maps.Marker({ position: uluru, map: map, });
マーカーについて詳しくは、次の記事をご覧ください。
ステップ 3: API キーを取得する
このセクションでは、独自の API キーを使用して、Maps JavaScript API に対してアプリを認証する方法について説明します。
次のステップに従って、API キーを取得します。
Google Cloud Console に移動します。
プロジェクトを作成または選択します。
[続行] をクリックして、API と関連サービスを有効にします。
[認証情報] ページで API キーを取得します(API キーの制限も設定します)。制限のない既存の API キーまたはブラウザの制限が設定されたキーがある場合は、そのキーを使用することもできます。
割り当ての盗用を防ぎ、API キーを保護する方法については、API キーの使用をご覧ください。
課金を有効化します。詳細については、使用量と課金をご覧ください。
このチュートリアルのページにあるコード全体をテキスト エディタにコピーします。
URL の
key
パラメータの値を、実際の API キー(上記のステップで取得した API キー)に置き換えます。<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"> </script>
このファイルは、
.html
で終わる名前(index.html
など)で保存します。HTML ファイルをパソコンからウェブブラウザにドラッグして、ブラウザで読み込みます。ほとんどのオペレーティング システムでは、HTML ファイルをダブルクリックしても同じ操作が可能です。
ヒントとトラブルシューティング
- スタイルやプロパティなどのオプションを微調整して、地図をカスタマイズできます。地図のカスタマイズについて詳しくは、スタイルと地図上への図形描画に関するガイドをご覧ください。
- ウェブブラウザでデベロッパー ツール コンソールを使用すると、コードをテストして実行したり、エラーレポートを確認したり、コードの問題を解決したりできます。
- Chrome でコンソールを開くには、キーボード ショートカットを使用します。
Mac の場合は Command+Option+J キー、Windows の場合は Ctrl+Shift+J キーです。 Google マップ上のビジネス拠点の緯度と経度の座標を取得する手順は次のとおりです。
- ブラウザで Google マップを開きます。
- 地図上で、座標が必要な場所の正確な位置を右クリックします。
- 表示されるコンテキスト メニューから [この場所について] を選択します。地図画面の下部にカードが表示されます。カードの最後の行で緯度と経度の座標を確認します。
ジオコーディング サービスを使用すると、住所を緯度と経度の座標に変換できます。デベロッパー ガイドで、ジオコーディング サービスの利用方法について詳しく説明しています。