Как добавить карту Google на веб-страницу

Вы можете добавить карту Google на страницу с помощью HTML, CSS или кода JavaScript. В этой статье рассказывается, как добавить карту на веб-страницу и получить доступ к экземпляру карты программным способом.

Обзор

Чтобы карта загрузилась, на веб-странице нужно:

  • Загрузить Maps JavaScript API с помощью начального загрузчика. Сюда передается ваш ключ API. Его можно добавить в HTML или исходные файлы JavaScript.
  • Поместить карту на страницу HTML и добавить нужные стили CSS.
  • Загрузить библиотеку maps и инициализировать карту.

Как добавить карту с помощью элемента gmp-map

Элемент gmp-map – это предпочтительный способ добавить карту Google на веб-страницу. Это пользовательский элемент HTML, созданный с помощью веб-компонентов. Чтобы добавить карту на веб-страницу с помощью элемента gmp-map, сделайте следующее:

  1. Добавьте элемент script, содержащий загрузчик, на страницу HTML или в исходный файл JavaScript или TypeScript без элемента script. Настройте загрузчик с помощью ключа API и других параметров. Вы можете выбрать динамический импорт библиотеки или прямую загрузку скрипта. В примере ниже показано, как добавить динамическую загрузку скрипта на страницу 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>

    Подробнее о загрузке Google Maps JavaScript API…

  2. Добавьте на страницу HTML элемент gmp-map. Укажите координаты широты и долготы для center (обязательно), значение масштаба для zoom (обязательно) и map-id, если необходимо (например, для расширенных маркеров).

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

Полный пример кода

TypeScript

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

    // Access the map.
    const mapElement = document.querySelector('gmp-map')!;
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();

JavaScript

async function init() {
    // Import the needed libraries.
    await google.maps.importLibrary('maps');

    // Access the map.
    const mapElement = document.querySelector('gmp-map');
    // Access the underlying map object.
    const innerMap = mapElement.innerMap;

    console.log({ mapElement, innerMap });
}

void init();

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>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </script>
    </head>

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

Как добавить карту с помощью элемента div и кода JavaScript

Чтобы добавить карту на веб-страницу с помощью элемента div, сделайте следующее:

  1. Добавьте элемент script, содержащий загрузчик, на страницу HTML или в исходный файл JavaScript или TypeScript без элемента script. Настройте загрузчик с помощью ключа API и других параметров. Вы можете выбрать динамический импорт библиотеки или прямую загрузку скрипта. В примере ниже показано, как добавить динамическую загрузку на 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>

    Подробнее о загрузке Google Maps JavaScript API…

  2. Добавьте на страницу HTML элемент div, который будет содержать карту.

    <div id="map"></div>
  3. В CSS задайте высоту карты 100 %. Атрибут CSS height необходим для того, чтобы карта была видна.

    #map {
      height: 100%;
    }
  4. В файле JS или TS создайте функцию для загрузки библиотеки maps и инициализации карты. Укажите широту и долготу для center (центр) и уровень масштабирования для zoom. При необходимости добавьте идентификатор карты, используя свойство mapId. Поскольку по умолчанию будет использоваться растровая карта, запросите векторную карту, указав параметр "VECTOR". Векторный тип карты рекомендуется для лучшего взаимодействия с пользователем, поскольку он обеспечивает более высокую детализацию изображения, а также позволяет управлять наклоном и направлением на карте.

    TypeScript

    let map: google.maps.Map;
    async function init(): Promise<void> {
        // Import the needed libraries
        const { Map } = 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',
        });
    
        console.log(map);
    }
    
    void init();

    JavaScript

    let map;
    async function init() {
        // Import the needed libraries
        const { Map } = 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',
        });
    
        console.log(map);
    }
    
    void init();

Посмотреть полный пример исходного кода

TypeScript

let map: google.maps.Map;
async function init(): Promise<void> {
    // Import the needed libraries
    const { Map } = 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',
    });

    console.log(map);
}

void init();

JavaScript

let map;
async function init() {
    // Import the needed libraries
    const { Map } = 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',
    });

    console.log(map);
}

void init();

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>

        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY" 
            });
        </script>
    </head>

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

Как задавать и получать свойства экземпляра карты

Чтобы взаимодействовать с экземпляром карты, выберите содержащий его элемент. Код для этого будет отличаться в зависимости от того, использовали ли вы элемент gmp-map или элемент div.

Как получить экземпляр карты из элемента gmp-map

Чтобы получить экземпляр карты при использовании элемента gmp-map, используйте document.querySelector для получения экземпляра mapElement, как показано ниже.

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

Затем задайте свойства для экземпляра mapElement:

mapElement.zoom = 8;

Класс MapElement использует класс Map внутри себя. Чтобы получить доступ к классу Map, используйте свойство MapElement.innerMap, как показано ниже:

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

Как получить экземпляр карты из элемента div

При использовании элемента div получите экземпляр карты и задайте параметры во время инициализации:

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

После инициализации задайте параметры экземпляра map, как показано ниже.

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