Dodawanie mapy Google do strony internetowej

Mapę Google możesz dodać do strony internetowej za pomocą kodu HTML, CSS i JavaScript. Na tej stronie pokazujemy, jak dodać do strony internetowej mapę na 2 sposoby: za pomocą niestandardowego elementu HTML gmp-map lub elementu div.

Przegląd

Aby wczytać mapę, strona internetowa musi spełniać te warunki:

  • Wczytaj interfejs Maps JavaScript API za pomocą programu wczytywania. To w tym miejscu jest przekazywany klucz interfejsu API i można go dodać do źródłowych plików HTML lub JavaScript.
  • Dodaj mapę do strony HTML i dodaj wymagane style CSS.
  • Wczytaj bibliotekę maps i zainicjuj mapę.

Dodaj mapę za pomocą elementu gmp-map

Element gmp-map to niestandardowy element HTML utworzony za pomocą komponentów sieciowych. Aby dodać do strony internetowej mapę za pomocą elementu gmp-map, wykonaj te czynności.

  1. Na stronie HTML dodaj element script zawierający wczytanie skonfigurowane za pomocą klucza interfejsu API i wszelkie inne opcje. W tym przykładowym pliku wczytywania pominięto parametr callback, ponieważ nie jest potrzebny.

    <script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&loading=async&libraries=map,marker">
    
  2. Na stronie HTML dodaj element gmp-map. Określ współrzędne szerokości i długości geograficznej dla elementu center oraz wartość powiększenia dla zoom. W tym przykładzie określono również atrybut stylu height.

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

Uzupełnij przykładowy kod

<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>

Dodaj mapę za pomocą elementu div i JavaScriptu

Element div nadal obsługuje wczytywanie map. Aby dodać do strony internetowej mapę za pomocą elementu div, wykonaj poniższe czynności.

  1. Na stronie HTML dodaj element script zawierający program wczytywania skonfigurowanych z Twoim kluczem interfejsu API i wszelkie inne opcje. Możesz też dodać kod programu wczytywania bezpośrednio do pliku TypeScript lub JavaScript, pomijając tagi script.

    <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. Na stronie HTML dodaj element div, który będzie zawierał mapę.

    <div id="map"></div>
    
  3. W pliku CSS ustaw wysokość mapy na 100%.

    #map {
      height: 100%;
    }
    
  4. W pliku JavaScript utwórz funkcję wczytywania biblioteki maps i zainicjowania mapy. Określ współrzędne szerokości i długości geograficznej miejsca center oraz poziom powiększenia dla tego elementu: 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();

Uzupełnij przykładowy kod

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>

Wypróbuj fragment