Google Maps-Karten einer Webseite hinzufügen

Sie können einer Webseite eine Google-Karte mithilfe von HTML-, CSS- und JavaScript-Code hinzufügen. Auf dieser Seite wird auf zwei Arten eine Karte zu einer Webseite hinzugefügt: über das benutzerdefinierte HTML-Element gmp-map und über ein div-Element.

Überblick

Damit eine Karte geladen werden kann, muss Ihre Webseite folgende Voraussetzungen erfüllen:

  • Laden Sie die Maps JavaScript API mit einem Bootstrap-Ladeprogramm. Hier wird Ihr API-Schlüssel übergeben, der entweder den HTML- oder JavaScript-Quelldateien hinzugefügt werden kann.
  • Fügen Sie die Karte der HTML-Seite und die erforderlichen CSS-Stile hinzu.
  • Laden Sie die maps-Bibliothek und initialisieren Sie die Karte.

Karte mit einem gmp-map-Element hinzufügen

Das gmp-map-Element ist ein benutzerdefiniertes HTML-Element, das mithilfe von Webkomponenten erstellt wird. So fügen Sie einer Webseite mit einem gmp-map-Element eine Karte hinzu:

  1. Fügen Sie auf der HTML-Seite ein script-Element hinzu, das das mit Ihrem API-Schlüssel und alle anderen Optionen konfigurierte Bootstrap enthält. Im folgenden Beispiel für Bootstrap wurde der Parameter callback weggelassen, da er nicht benötigt wird.

    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
    
  2. Fügen Sie auf der HTML-Seite ein gmp-map-Element hinzu. Geben Sie für center die Breiten- und Längengradkoordinaten und für zoom einen Zoomwert an. In diesem Beispiel wurde auch das Stilattribut height angegeben.

    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

Vollständiges Codebeispiel

<html>
  <head>
    <title>Add a Map using HTML</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>
    <gmp-map
      center="37.4220656,-122.0840897"
      zoom="10"
      map-id="DEMO_MAP_ID"
      style="height: 400px"
    ></gmp-map>

    <!-- 
      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.
      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=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=beta"
      defer
    ></script>
  </body>
</html>

Karte mit einem div-Element und JavaScript hinzufügen

Das div-Element wird weiterhin zum Laden von Karten unterstützt. So fügen Sie einer Webseite mit einem div-Element eine Karte hinzu:

  1. Fügen Sie auf der HTML-Seite ein script-Element hinzu, das das Bootstrap-Ladeprogramm enthält, das mit Ihrem API-Schlüssel und anderen Optionen konfiguriert wurde. Alternativ können Sie den Code des Bootstrap-Ladeprogramms direkt in eine TypeScript- oder JavaScript-Datei ohne die script-Tags einfügen.

    <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>
    
  2. Fügen Sie auf der HTML-Seite ein div-Element hinzu, das die Karte enthält.

    <div id="map"></div>
    
  3. Legen Sie im CSS-Code die Kartenhöhe auf 100 % fest.

    #map {
      height: 100%;
    }
    
  4. Erstellen Sie in der JavaScript-Datei eine Funktion zum Laden der maps-Bibliothek und zum Initialisieren der Karte. Geben Sie Breiten- und Längengradkoordinaten für center und die Zoomstufe für zoom an.

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();

Vollständiges Codebeispiel

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>
    <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>
    <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: "weekly"});</script>
  </body>
</html>

Testbeispiel