HTML、CSS、JavaScript コードを使用して、Google マップをウェブページに追加できます。このページでは、ウェブページに地図を追加する 2 つの方法(gmp-map カスタム HTML 要素を使用する方法と div 要素を使用する方法)を説明します。
概要
地図を読み込むには、ウェブページで次のことを行う必要があります。
- ブートストラップ ローダを使用して Maps JavaScript API を読み込む。ここで API キーが渡され、HTML または JavaScript のソースファイルに追加されます。
- 地図を HTML ページに追加し、必要な CSS スタイルを追加する。
- mapsライブラリを読み込み、地図を初期化する。
gmp-map 要素を使って地図を追加する
gmp-map 要素は、ウェブ コンポーネントを使用して作成されるカスタム HTML 要素です。gmp-map 要素を使用して地図をウェブページに追加する手順は次のとおりです。
- HTML ページで、API キーとその他のオプションで構成されたブートストラップを含む - script要素を追加します。- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=maps,marker" defer ></script> 
- HTML ページで、 - gmp-map要素を追加します。- centerには緯度と経度の座標を指定し、- zoomにはズーム値を指定します。この例では、- heightスタイル属性も指定されています。- <gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID" style="height: 400px" ></gmp-map> 
コードサンプルの全文
<html>
  <head>
    <title>Add a Map using HTML</title>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>
   <!-- 
      The `defer` attribute causes the script 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. See
      https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&libraries=maps,marker&v=weekly"
      defer
    ></script>
  </body>
</html>div 要素と JavaScript を使って地図を追加する
div 要素を使用して地図をウェブページに追加する手順は次のとおりです。
- HTML ページで、API キーとその他のオプションで構成されたブートストラップ ローダを含む - script要素を追加します。または、- scriptタグを除いた TypeScript ファイルまたは JavaScript ファイルに、ブートストラップ ローダのコードを直接追加します。- <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> 
- HTML ページで、 - div要素を追加して、地図を含めます。- <div id="map"></div> 
- CSS で地図の高さを 100% に設定します。 - #map { height: 100%; } 
- JavaScript ファイルで、 - mapsライブラリを読み込んで地図を初期化する関数を作成します。- centerには緯度と経度の座標を指定し、- zoomには使用するズームレベルを指定します。- let map; async function initMap() { const { Map } = await google.maps.importLibrary("maps"); map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } initMap(); 
コードサンプルの全文
TypeScript
let map: google.maps.Map; async function initMap(): Promise<void> { const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; map = new Map(document.getElementById("map") as HTMLElement, { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } initMap();
JavaScript
let map; async function initMap() { const { Map } = await google.maps.importLibrary("maps"); map = new Map(document.getElementById("map"), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } 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>
  </head>
  <body>
    <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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
  </body>
</html>