您可以使用 HTML、CSS 和 JavaScript 代码将 Google 地图添加到网页中。 本页面介绍了如何向网页添加地图,然后以编程方式访问地图实例。
概览
要加载地图,网页必须完成以下操作:
- 使用引导加载程序 加载 Maps JavaScript API。此过程中会传递 API 密钥,可将密钥添加到 HTML 或 JavaScript 源文件中。
- 将地图添加到 HTML 页面中,并添加需要的 CSS 样式。
- 加载
maps库并初始化地图。
使用 gmp-map 元素添加地图
gmp-map 元素是向网页添加 Google 地图的首选方式。它是一种使用 Web 组件创建的自定义 HTML 元素。若要使用
gmp-map 元素将地图添加到网页中,请按以下步骤操作。
将包含引导加载程序的
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>
在 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 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>试用选段
使用 div 元素和 JavaScript 代码添加地图
若要使用 div 元素将地图添加到网页中,请按以下步骤操作。
将包含引导加载程序的
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>
在 HTML 页面上,添加
div元素来包含地图。<div id="map"></div>
在 CSS 中,将地图高度设置为 100%。地图必须具有 CSS
height属性,才能显示出来。#map { height: 100%; }
在 JS 或 TS 文件中,创建一个函数来加载
maps库和初始化地图。为center指定纬度和经度坐标,为zoom指定缩放级别。如果需要,请使用mapId属性添加地图 ID。由于地图默认采用光栅,因此请通过指定“VECTOR”地图选项来请求矢量地图;建议使用矢量地图类型,以获得最佳用户体验,因为它不仅能提供更高的视觉保真度,还能控制地图上的倾斜度和朝向。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();
查看完整的示例源代码
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>试用选段
设置和获取地图实例的属性
如需与地图实例互动,请选择包含该实例的元素。执行此操作的代码因您使用的是 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 类;使用 MapElement.innerMap 属性访问 Map 类
,如下所示:
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,
});