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 uzyskać dostęp do instancji mapy za pomocą kodu.
- Dodawanie mapy za pomocą elementu
gmp-map - Dodawanie mapy za pomocą elementu
divi JavaScriptu - Ustawianie i pobieranie właściwości instancji mapy
Przegląd
Aby wczytać mapę, strona internetowa musi wykonać te czynności:
- Wczytaj interfejs Maps JavaScript API za pomocą narzędzia do wczytywania. 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ę
mapsi 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.
Dodaj element
scriptzawierający bootstrap do strony HTML lub dodaj go do pliku źródłowego JavaScript lub TypeScript bez elementuscript. Skonfiguruj wczytywanie początkowe za pomocą klucza interfejsu API i innych opcji. Możesz wybrać dynamiczne importowanie biblioteki lub bezpośrednie wczytywanie skryptu. Ten przykład pokazuje, jak dodać do strony HTML bootstrapa dynamicznego wczytywania skryptu:<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 Maps JavaScript API
Na stronie HTML dodaj element
gmp-map. Określ współrzędne szerokości i długości geograficznej dla parametrucenter(wymagany), wartość powiększenia dla parametruzoom(wymagany) i w razie potrzeby parametrmap-id(jest on wymagany w przypadku niektórych funkcji, np. znaczników zaawansowanych).
<gmp-map center="-34.397,150.644" zoom="8" mapId="DEMO_MAP_ID"> </gmp-map>
Kompletny przykładowy kod
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>Dodawanie mapy za pomocą elementu div i JavaScriptu
Aby dodać mapę do strony internetowej za pomocą elementu div, wykonaj te czynności.
Dodaj element
scriptzawierający bootstrap do strony HTML lub dodaj go do pliku źródłowego JavaScript lub TypeScript bez elementuscript. Skonfiguruj wczytywanie początkowe za pomocą klucza interfejsu API i innych opcji. Możesz wybrać dynamiczne importowanie 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 Maps JavaScript API
Na stronie HTML dodaj element
div, który będzie zawierać mapę.<div id="map"></div>
W CSS ustaw wysokość mapy na 100%. Atrybut CSS
heightjest wymagany, aby mapa była widoczna.#map { height: 100%; }
W pliku JS lub TS utwórz funkcję, która wczytuje bibliotekę
mapsi inicjuje mapę. Określ współrzędne geograficzne dlacenteri poziom powiększenia dlazoom. W razie potrzeby dodaj identyfikator mapy za pomocą właściwościmapId. Mapa domyślnie będzie rastrowa, więc aby poprosić o mapę wektorową, określ opcję mapy „VECTOR”. Typ mapy wektorowej jest zalecany ze względu na lepszą jakość obrazu oraz możliwość sterowania pochyleniem i kierunkiem na mapie.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();
Zobacz pełny przykładowy kod źródłowy
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>Ustawianie i pobieranie właściwości instancji mapy
Aby wejść w interakcję z instancją mapy, wybierz element zawierający. Kod, który to umożliwia, zależy od tego, czy użyto elementu gmp-map czy div.
Pobieranie instancji mapy z elementu gmp-map
Aby uzyskać instancję mapy podczas korzystania z elementu gmp-map, użyj elementu 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 korzysta z klasy Map. Dostęp do klasy Map można uzyskać 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, uzyskaj 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 zainicjowaniu ustaw opcje w instancji map, jak pokazano poniżej:
map.setOptions({
zoom: 8,
});