简介
本教程介绍了如何向网页添加带标记的简单 Google 地图,适合掌握了 HTML 和 CSS 的初级或中级知识的人员, 对 JavaScript 有一点了解。
下面便是您将在本教程的指导下创建的地图。标记位于乌鲁鲁卡塔丘塔国家公园中的乌鲁鲁(也称为“艾尔斯岩”)。
入门指南
在网页上创建带标记的 Google 地图需要执行以下三个步骤:
您需要一个网络浏览器。请根据所用平台从受支持的浏览器列表中选择一个常见的浏览器,例如 Google Chrome(推荐)、Firefox、Safari 或 Edge。
第 1 步:获取 API 密钥
本部分介绍如何使用您的 API 密钥对应用进行身份验证,以便使用 Maps JavaScript API。
请按照下列步骤获取 API 密钥:
前往 Google Cloud 控制台。
创建或选择一个项目。
点击继续,启用 API 和任何相关服务。
在凭据页面上,获取 API 密钥(并设置 API 密钥限制)。注意:如果您已有不受限的 API 密钥或存在浏览器限制的密钥,可以使用相应密钥。
如需防止配额盗用并保护 API 密钥,请参阅使用 API 密钥。
启用结算功能。如需了解详情,请参阅用量和结算。
获得 API 密钥后,点击“YOUR_API_KEY”将密钥添加到以下代码段中。复制并粘贴引导加载程序脚本标记,以供自己使用 网页中。
<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>
第 2 步:创建 HTML 网页
下方代码可创建一个基本的 HTML 网页:
<!doctype html> <!-- @license Copyright 2019 Google LLC. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 --> <html> <head> <title>Add Map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>
请注意,这是一个非常基本的网页,包含一个三级标题 (h3
) 和单个 div
元素。您可以随意向该网页添加任何内容。
了解代码
以下代码可创建一个包含头部板块和正文板块的 HTML 网页。
<html> <head> </head> <body> </body> </html>
您可以使用以下代码在地图上方添加一个三级标题。
<h3>My Google Maps Demo</h3>
以下代码可为 Google 地图定义一个页面区域。
<!--The div element for the map --> <div id="map"></div>
在教程的这一阶段,由于您尚未添加地图,因此 div
仅显示为一个灰色块。以下代码描述了用于设置 div
大小和颜色的 CSS。
/* Set the size of the div element that contains the map */ #map { height: 400px; /* The height is 400 pixels */ width: 100%; /* The width is the width of the web page */ }
在以上代码中,style
元素用于设置地图的 div
大小。将 div
的宽度和高度设置为大于 0px 的值,才能让地图显示出来。在本例中,div
的高度设置为 400 像素,宽度设置为 100%,即按网页的完整宽度显示地图。
引导程序加载器会准备 Maps JavaScript API 以进行加载(在调用 importLibrary()
之前不会加载任何库)。
<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>
如需了解如何获取自己的 API 密钥,请参阅第 3 步:获取 API 密钥。
第 3 步:添加带标记的地图
本部分介绍如何将 Maps JavaScript API 加载到您的网页中,以及如何自行编写 JavaScript,以利用 API 添加带标记的地图。
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", }); } initMap();
在以上代码中,调用 initMap()
函数时会加载 Map
和 AdvancedMarkerView
库。
了解代码
以下代码会构造一个新的 Google 地图对象,并向该地图添加中心和缩放级别等属性。请参阅相关文档,了解其他属性选项。
TypeScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } );
JavaScript
// The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", });
在以上代码中,new Map()
会创建一个新的 Google 地图对象。center
属性用于向 API 指示地图的中心位置。
详细了解如何获取纬度/经度坐标,或如何将地址转换为地理坐标。
zoom
属性用于指定地图的缩放级别。0 是最低缩放级别,会显示整个地球。调高缩放级别值,就能以更高的分辨率放大地球。
以下代码会在地图上放置标记。position
属性用于设置标记的位置。
TypeScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' });
JavaScript
// The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", });
完整示例代码
在此处查看完整的示例代码:
TypeScript
// Initialize and add the map let map; async function initMap(): Promise<void> { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary; const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary; // The map, centered at Uluru map = new Map( document.getElementById('map') as HTMLElement, { zoom: 4, center: position, mapId: 'DEMO_MAP_ID', } ); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: 'Uluru' }); } initMap();
JavaScript
// Initialize and add the map let map; async function initMap() { // The location of Uluru const position = { lat: -25.344, lng: 131.031 }; // Request needed libraries. //@ts-ignore const { Map } = await google.maps.importLibrary("maps"); const { AdvancedMarkerElement } = await google.maps.importLibrary("marker"); // The map, centered at Uluru map = new Map(document.getElementById("map"), { zoom: 4, center: position, mapId: "DEMO_MAP_ID", }); // The marker, positioned at Uluru const marker = new AdvancedMarkerElement({ map: map, position: position, title: "Uluru", }); } 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>Add Map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> </head> <body> <h3>My Google Maps Demo</h3> <!--The div element for the map --> <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: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script> </body> </html>
试用示例
详细了解标记:
提示和问题排查
- 您可以通过调整样式和属性等选项来自定义地图。如需详细了解如何自定义地图,请参阅有关样式设置和在地图上绘制的指南。
- 在网络浏览器中使用开发者工具控制台来测试和运行代码、阅读错误报告并解决代码存在的问题。
- 使用以下键盘快捷键在 Chrome 中打开控制台:
Command+Option+J(在 Mac 上)或 Ctrl+Shift+J(在 Windows 上)。 按照以下步骤操作,获取 Google 地图上某个位置的纬度和经度坐标。
- 在浏览器中打开 Google 地图。
- 在地图上右键点击需要坐标的确切位置。
- 从显示的上下文菜单中选择这儿有什么?。地图会在屏幕底部显示一张卡片。在卡片的最后一行找到纬度和经度坐标。
您可以使用地理编码服务将地址转换为纬度和经度坐标。开发者指南详细介绍了如何开始使用地理编码服务。