向网站添加带标记的 Google 地图

简介

本教程介绍了如何向网页添加带标记的简单 Google 地图。其适用对象为掌握了 HTML 和 CSS 的初级或中级知识并对 JavaScript 略有了解的人士。有关创建地图的高级指南,请参阅开发者指南

下面便是您将在本教程的指导下创建的地图。标记位于乌鲁鲁卡塔丘塔国家公园中的乌鲁鲁(也称为“艾尔斯岩”)。

下文显示了创建本教程中的地图所需的完整代码。

TypeScript

// Initialize and add the map
function initMap(): void {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: uluru,
    }
  );

  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// Initialize and add the map
function initMap() {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

window.initMap = initMap;

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 */
}

HTML

<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

    <!--
      The `defer` attribute causes the callback 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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

试用示例

入门指南

在网页上创建带标记的 Google 地图需要执行以下三个步骤:

  1. 创建 HTML 网页
  2. 添加带标记的地图
  3. 获取 API 密钥

您需要一个网络浏览器。请根据所用平台从受支持的浏览器列表中选择一个常见的浏览器,例如 Google Chrome(推荐)、Firefox、Safari 或 Edge。

第 1 步:创建 HTML 网页

下方代码可创建一个基本的 HTML 网页:

<!DOCTYPE html>
<!--
 @license
 Copyright 2019 Google LLC. All Rights Reserved.
 SPDX-License-Identifier: Apache-2.0
-->
<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

    <!--
      The `defer` attribute causes the callback 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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></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。

/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */
/* 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%,可按网页的完整宽度显示地图。

第 2 步:添加带标记的地图

本部分介绍如何将 Maps JavaScript API 加载到您的网页中,以及如何自行编写 JavaScript,以利用 API 添加带标记的地图。

TypeScript

// Initialize and add the map
function initMap(): void {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 4,
      center: uluru,
    }
  );

  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;

JavaScript

// Initialize and add the map
function initMap() {
  // The location of Uluru
  const uluru = { lat: -25.344, lng: 131.031 };
  // The map, centered at Uluru
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: uluru,
  });
  // The marker, positioned at Uluru
  const marker = new google.maps.Marker({
    position: uluru,
    map: map,
  });
}

window.initMap = initMap;

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 */
}

HTML

<html>
  <head>
    <title>Add Map</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <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>

    <!--
      The `defer` attribute causes the callback 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
      with https://www.npmjs.com/package/@googlemaps/js-api-loader.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initMap&v=weekly"
      defer
    ></script>
  </body>
</html>

试用示例

了解代码

在下面的代码中,script 会从指定网址加载 API。

<script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

在上面的代码中,callback 参数用于在 API 加载后执行 initMap 函数。async 属性让浏览器能够在 API 加载期间继续解析网页的其余部分。加载完成后,浏览器将暂停并立即执行脚本。key 参数包含您的 API 密钥。

如需了解稍后如何获取自己的 API 密钥,请参阅第 3 步:获取 API 密钥

下面的代码包含 initMap 函数,该函数可在网页加载时初始化并添加地图。您可以使用 script 标记添加您自己的包含 initMap 函数的 JavaScript。

  function initMap() {}

添加 document.getElementById() 函数,以在网页上找到地图 div

下面的代码会构造一个新的 Google 地图对象,并向该地图添加包括中心和缩放级别在内的属性。请参阅相关文档,了解其他属性选项

TypeScript

// The location of Uluru
const uluru = { lat: -25.344, lng: 131.031 };
// The map, centered at Uluru
const map = new google.maps.Map(
  document.getElementById("map") as HTMLElement,
  {
    zoom: 4,
    center: uluru,
  }
);

JavaScript

// The location of Uluru
const uluru = { lat: -25.344, lng: 131.031 };
// The map, centered at Uluru
const map = new google.maps.Map(document.getElementById("map"), {
  zoom: 4,
  center: uluru,
});

在上面的代码中,new google.maps.Map() 会创建一个新的 Google 地图对象。center 属性用于向 API 指示地图的中心位置。

详细了解如何获取纬度/经度坐标,或如何将地址转换为地理坐标

zoom 属性用于指定地图的缩放级别。缩放级别 0 是最低缩放级别,会显示整个地球。调高缩放级别值,就能以更高的分辨率放大地球。

下面的代码会在地图上放置标记。position 属性用于设置标记的位置。

TypeScript

// The marker, positioned at Uluru
const marker = new google.maps.Marker({
  position: uluru,
  map: map,
});

JavaScript

// The marker, positioned at Uluru
const marker = new google.maps.Marker({
  position: uluru,
  map: map,
});

详细了解标记:

第 3 步:获取 API 密钥

本部分介绍如何使用您的 API 密钥向 Maps JavaScript API 对应用进行身份验证。

请按照下列步骤获取 API 密钥:

  1. 前往 Google Cloud 控制台

  2. 创建或选择一个项目。

  3. 点击继续,启用 API 和任何相关服务。

  4. 凭据页面上,获取 API 密钥(并设置 API 密钥限制)。注意:如果您已有不受限的 API 密钥或存在浏览器限制的密钥,可以使用该密钥。

  5. 若想防止配额盗用并保护 API 密钥,请参阅使用 API 密钥

  6. 启用结算功能。如需了解详情,请参阅使用量和结算

  7. 将此页面上本教程的完整代码复制到文本编辑器中。

  8. 将网址中 key 参数的值替换为您自己的 API 密钥(即您刚刚获取的 API 密钥)。

    <script async
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
    

  9. 使用以 .html 结尾的名称保存该文件,例如 index.html

  10. 将该 HTML 文件从桌面拖放到网络浏览器上进行加载。在大多数操作系统上,也可双击该文件进行加载。

提示和问题排查

  • 您可以通过调整样式和属性之类的选项对地图进行自定义。如需详细了解如何自定义地图,请参阅有关样式设置在地图上绘制的指南。
  • 在网络浏览器中使用开发者工具控制台来测试和运行代码、阅读错误报告并解决代码存在的问题。
  • 使用以下键盘快捷键在 Chrome 中打开控制台:
    Command+Option+J(在 Mac 上)或 Ctrl+Shift+J(在 Windows 上)。
  • 按照以下步骤操作,获取 Google 地图上某个位置的纬度和经度坐标。

    1. 在浏览器中打开 Google 地图。
    2. 在地图上右键点击需要坐标的确切位置。
    3. 从显示的上下文菜单中选择这儿有什么?。地图会在屏幕底部显示一张卡片。在卡片的最后一行找到纬度和经度坐标。
  • 您可以使用地理编码服务将地址转换为纬度和经度坐标。开发者指南详细介绍了如何开始使用地理编码服务