您可以使用 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 src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=maps,marker" defer ></script>
在 HTML 页面上添加
gmp-map元素。为center指定纬度和经度坐标(必需),为zoom指定缩放值(必需),并根据需要指定map-id(对于某些功能(例如高级标记),这是必需的)。必须设置 CSSheight属性,地图才能显示。可以在 HTML 或 CSS 中指定。在此示例中,为简单起见,height样式属性是在 HTML 中指定的。<gmp-map center="37.4220656,-122.0840897" zoom="10" map-id="DEMO_MAP_ID" style="height: 400px" ></gmp-map>
完整示例代码
<html>
<head>
<title>Add a Map using HTML</title>
<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 script 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=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&libraries=maps,marker&v=weekly"
defer
></script>
</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%; }
在 JavaScript 文件中,创建一个函数来加载
maps库和初始化地图。为center指定纬度和经度坐标,为zoom指定缩放级别。如果需要,请使用map-id属性添加地图 ID。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();
完整示例代码
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>
<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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script>
</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 实例并在初始化时设置选项:
map = new google.maps.Map(document.getElementById("map"), {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
mapTypeControl: false,
});
初始化完成后,按如下所示设置 map 实例的选项:
map.setOptions({
zoom: 8,
});