Dodawanie mapy Google do strony internetowej

Mapę Google możesz dodać do strony internetowej za pomocą kodu HTML, CSS i JavaScript. Na tej stronie dowiesz się, jak dodać mapę do strony internetowej, a następnie programowo uzyskać dostęp do instancji mapy.

Przegląd

Aby wczytać mapę, strona internetowa musi wykonać te czynności:

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

Dodawanie mapy za pomocą elementu gmp-map

Element gmp-map to preferowany sposób dodawania mapy Google do strony internetowej. Jest to niestandardowy element HTML utworzony za pomocą komponentów internetowych. Aby dodać mapę do strony internetowej za pomocą elementu gmp-map, wykonaj te czynności.

  1. Dodaj element script zawierający bootstrap do strony HTML lub dodaj go do pliku źródłowego JavaScript lub TypeScript bez elementu script. Skonfiguruj bootstrap za pomocą klucza interfejsu API i innych opcji. Możesz wybrać dynamiczny import biblioteki lub bezpośrednie wczytywanie skryptu. Ten przykład pokazuje, jak dodać dynamiczny skrypt wczytujący bootstrap do strony HTML:

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

    Więcej informacji o wczytywaniu interfejsu Google Maps JavaScript API

  2. Na stronie HTML dodaj element gmp-map. Określ współrzędne szerokości i długości geograficznej dla center (wymagane), wartość powiększenia dla zoom (wymagane) oraz map-id, jeśli jest to potrzebne (jest wymagane w przypadku niektórych funkcji, takich jak znaczniki zaawansowane).

<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
</gmp-map>

Kompletny przykładowy kod

TypeScript

async function initMap(): Promise<void> {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Create the map.
    const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;
}

initMap();

JavaScript

async function initMap() {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');
    // Create the map.
    const mapElement = document.querySelector('gmp-map');
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;
}
initMap();

CSS

/* 
 * 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>
        <!-- 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>
    </head>

    <body>
        <gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID">
        </gmp-map>
    </body>
</html>

Wypróbuj przykład

Dodawanie mapy za pomocą elementu div i JavaScript

Aby dodać mapę do strony internetowej za pomocą elementu div, wykonaj te czynności.

  1. Dodaj element script zawierający bootstrap do strony HTML lub dodaj go do pliku źródłowego JavaScript lub TypeScript bez elementu script. Skonfiguruj bootstrap za pomocą klucza interfejsu API i innych opcji. Możesz wybrać dynamiczny import biblioteki lub bezpośrednie wczytywanie skryptu. Ten przykład pokazuje, jak dodać dynamiczny bootstrap do strony HTML:

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

    Więcej informacji o wczytywaniu interfejsu Google Maps JavaScript API

  2. Na stronie HTML dodaj element div, który będzie zawierać mapę.

    <div id="map"></div>
  3. W CSS ustaw wysokość mapy na 100%. Aby mapa była widoczna, wymagany jest atrybut CSS height.

    #map {
      height: 100%;
    }
  4. W pliku JS lub TS utwórz funkcję wczytującą bibliotekę maps i inicjującą mapę. Określ współrzędne szerokości i długości geograficznej dla center oraz poziom powiększenia dla zoom. W razie potrzeby dodaj identyfikator mapy za pomocą właściwości mapId. Ponieważ mapa domyślnie będzie rastrowa, poproś o mapę wektorową, określając opcję mapy „VECTOR”. Typ mapy wektorowej jest zalecany, ponieważ zapewnia lepszą jakość wizualną oraz możliwość sterowania nachyleniem i kierunkiem na mapie.

    TypeScript

    let map: google.maps.Map;
    async function initMap(): Promise<void> {
        // Import the needed libraries
        const { Map, RenderingType } = (await google.maps.importLibrary(
            'maps'
        )) as google.maps.MapsLibrary;
    
        // Create a new map from the div with id="map".
        map = new Map(document.getElementById('map') as HTMLElement, {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
            renderingType: "VECTOR",
        });
    }
    
    initMap();

    JavaScript

    let map;
    async function initMap() {
        // Import the needed libraries
        const { Map, RenderingType } = (await google.maps.importLibrary('maps'));
        // Create a new map from the div with id="map".
        map = new Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8,
            renderingType: "VECTOR",
        });
    }
    initMap();

Zobacz pełny przykładowy kod źródłowy

TypeScript

let map: google.maps.Map;
async function initMap(): Promise<void> {
    // Import the needed libraries
    const { Map, RenderingType } = (await google.maps.importLibrary(
        'maps'
    )) as google.maps.MapsLibrary;

    // Create a new map from the div with id="map".
    map = new Map(document.getElementById('map') as HTMLElement, {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
        renderingType: "VECTOR",
    });
}

initMap();

JavaScript

let map;
async function initMap() {
    // Import the needed libraries
    const { Map, RenderingType } = (await google.maps.importLibrary('maps'));
    // Create a new map from the div with id="map".
    map = new Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8,
        renderingType: "VECTOR",
    });
}
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>

    <!-- 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>
</head>

<body>
    <div id="map"></div>
</body>

</html>

Wypróbuj przykład

Ustawianie i pobieranie właściwości instancji mapy

Aby korzystać z instancji mapy, wybierz element zawierający. Kod, który to robi, będzie się różnić w zależności od tego, czy używasz elementu gmp-map, czy elementu div.

Pobieranie instancji mapy z elementu gmp-map

Aby uzyskać instancję mapy podczas korzystania z elementu gmp-map, użyj document.querySelector aby pobrać instancję mapElement, jak pokazano tutaj.

const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;

Następnie ustaw właściwości instancji mapElement:

mapElement.zoom = 8;

Klasa MapElement wewnętrznie używa klasy Map. Dostęp do klasy Map uzyskasz za pomocą właściwości MapElement.innerMap, jak pokazano tutaj:

mapElement.innerMap.setOptions({
    mapTypeControl: false,
});

Pobieranie instancji mapy z elementu div

Gdy używasz elementu div, pobierz instancję mapy i ustaw opcje podczas inicjowania:

map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
    mapTypeControl: false,
});

Po inicjowaniu ustaw opcje instancji map, jak pokazano tutaj:

map.setOptions({
    zoom: 8,
});