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

简介

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

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


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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    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>
    <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>

    <!-- 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: "beta"});</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>

    <!-- 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: "beta"});</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_HERE",
    // Add other bootstrap parameters as needed, using camel case.
    // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
  });
</script>

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

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

本部分介绍如何将 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
    map: map,
    position: position,
    title: "Uluru",
  });
}

initMap();

在上面的代码中,调用 initMap() 函数时会加载 MapAdvancedMarkerView 库。

了解代码

下面的代码会构造一个新的 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 { AdvancedMarkerView } = 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 { AdvancedMarkerView } = 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 AdvancedMarkerView({
  map: map,
  position: position,
  title: 'Uluru'
});

JavaScript

// The marker, positioned at Uluru
const marker = new AdvancedMarkerView({
  map: map,
  position: position,
  title: "Uluru",
});

详细了解标记:

第 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>
      (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_HERE",
        // Add other bootstrap parameters as needed, using camel case.
        // Use the 'v' parameter to indicate the version to load (alpha, beta, weekly, etc.)
      });
    </script>
    
  9. 使用以 .html 结尾的名称保存该文件,例如 index.html

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

提示和问题排查

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

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