Skip to content

Google 地图 - 快速指南

本指南简要总结了 Maps JavaScript API 入门章节中涵盖的关键概念。

核心思想:在网页上显示一个基本地图。

  • 获取 API 密钥: 从 Google Cloud Console 获取,启用 Maps JavaScript API,并确保密钥安全。
  • HTML 结构: 创建一个 HTML 文件,其中包含一个具有特定 id (例如 id="map") 的 <div> 元素,并通过 CSS 设置其 height。
  • 加载 API: 使用 https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly 包含 API 脚本(使用 async defer)。
  • 回调函数: 定义一个 async function initMap() 函数,该函数将在 API 加载时执行。
  • 导入库: 在 initMap 中,使用 await google.maps.importLibrary("maps") 加载 Map 类。
  • 实例化地图: 创建地图对象:new google.maps.Map(document.getElementById('map'), { center: {lat: ..., lng: ...}, zoom: ..., mapId: 'YOUR_MAP_ID' });。

基本示例代码片段 (initMap 函数):

Section titled “基本示例代码片段 (initMap 函数):”
async function initMap() {
const position = { lat: -34.397, lng: 150.644 }; // Sydney
const { Map } = await google.maps.importLibrary("maps");
const map = new Map(document.getElementById("map"), {
zoom: 8,
center: position,
mapId: "DEMO_MAP_ID" // Use your Map ID for styling
});
}

核心思想:选择基础地图的视觉样式。

可用类型(通过 MapOptions 中的 mapTypeId 或 map.setMapTypeId() 设置):

Section titled “可用类型(通过 MapOptions 中的 mapTypeId 或 map.setMapTypeId() 设置):”
  • 'roadmap' (默认): 标准街道地图。
  • 'satellite': 航空/卫星照片。
  • 'hybrid': 叠加道路/标签的卫星照片。
  • 'terrain': 显示海拔、河流等物理起伏地图。

现代方法:使用链接到基于云的地图样式 (Cloud-based Map Styles) 的 mapId,可以在这些基本类型之外进行更丰富的视觉自定义。

const mapOptions = {
zoom: 11,
center: { lat: 48.8566, lng: 2.3522 }, // Paris
mapId: "DEMO_MAP_ID",
mapTypeId: 'terrain' // Show terrain view initially
};

核心思想:控制地图的放大倍数。

  • 初始: 在 MapOptions 中设置 zoom 属性(数字)。
  • 编程方式: 使用 map.setZoom(newZoomLevel);。
  • 获取当前: 使用 map.getZoom();。
  • 1: 世界
  • 5: 大陆 / 大国家
  • 10: 城市
  • 15: 街道
  • 20: 单个建筑物
const mapOptions = {
zoom: 15, // Street level detail
center: { lat: 51.5074, lng: -0.1278 }, // London
mapId: "DEMO_MAP_ID"
};

核心思想:以特定语言和格式显示地图标签和控件。

在 API 脚本 URL 中添加 language 和可选的 region 参数。

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly&language=ja&region=JP" async defer></script>
<!-- language=ja (Japanese), region=JP (Japan) -->
<!-- language=ja (日语), region=JP (日本) -->

支持的语言:请参阅官方列表。

核心思想:管理地图上的交互元素。

  • disableDefaultUI: true : 隐藏 所有 默认控件。
  • 单个控件(布尔值,除另有说明外默认值为 true):zoomControl, mapTypeControl, streetViewControl, fullscreenControl, rotateControl。
  • scaleControl: 默认值为 false,设置为 true 以显示地图比例尺。
  • 定位:使用 controlOptions (例如 zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM })。需要导入 ControlPosition。
const { Map, ControlPosition } = await google.maps.importLibrary("maps");
// ... in initMap ...
// ... 在 initMap 中 ...
const mapOptions = {
zoom: 12,
center: { lat: 37.7749, lng: -122.4194 }, // San Francisco
mapId: "DEMO_MAP_ID",
streetViewControl: false, // Hide Pegman
// 隐藏 Pegman
fullscreenControl: false, // Hide fullscreen button
// 隐藏全屏按钮
scaleControl: true, // Show scale
// 显示比例尺
mapTypeControlOptions: {
position: ControlPosition.TOP_RIGHT // Move map type selector
// 移动地图类型选择器
}
};

核心思想:在地图上指示特定点。

  • 导入库: const { Marker } = await google.maps.importLibrary("marker"); (并在脚本 URL 中添加 &libraries=marker)。
  • 实例化: new google.maps.Marker({ position: {lat:..., lng:...}, map: map, title: '可选提示文本' });。
  • 现代替代方案: AdvancedMarkerView 提供更多自定义和性能优势。
  • 动画: 设置 animation: google.maps.Animation.DROP 或 BOUNCE。
  • 自定义图标: 设置 icon: '图像URL' 或使用 Symbol 对象。
  • 可拖动: 设置 draggable: true。
  • 标签: 设置 label: 'A' 或一个 MarkerLabel 对象。
  • 移除: 调用 marker.setMap(null);。
const { Marker } = await google.maps.importLibrary("marker");
const { Animation } = await google.maps.importLibrary("maps"); // If using animation
// 如果使用动画
const marker = new Marker({
position: { lat: -33.8688, lng: 151.2093 }, // Sydney
map: map,
title: '悉尼歌剧院附近',
icon: 'https://maps.google.com/mapfiles/ms/icons/blue-dot.png',
animation: Animation.DROP
});

7. 形状(折线、多边形、圆形、矩形)

Section titled “7. 形状(折线、多边形、圆形、矩形)”

核心思想:在地图上绘制线条和区域。

  • 导入库: 通常是基础 maps 库的一部分,但如有需要请查阅特定类文档。
  • 实例化: 使用 new google.maps.Polyline({...}), Polygon({...}), Rectangle({...}), Circle({...})。
  • 关键属性:
  • - `path` (Polyline/Polygon): `{lat: ..., lng: ...}` 坐标数组。
  • - `bounds` (Rectangle): 一个 `google.maps.LatLngBounds` 对象。
  • - `center` & `radius` (Circle): 中心坐标和半径(单位:米)。
  • - `map: map`: 与地图关联。
  • - 样式选项:`strokeColor`, `strokeOpacity`, `strokeWeight`, `fillColor`, `fillOpacity`。
  • - 交互性:`editable: true`, `draggable: true`。
  • 移除: 调用 shape.setMap(null);。
const flightPlanCoordinates = [
{ lat: 37.772, lng: -122.214 },
{ lat: 21.291, lng: -157.821 },
{ lat: -18.142, lng: 178.431 },
{ lat: -33.951, lng: 151.177 }
];
const flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true, // Makes the line follow Earth's curvature
// 使线条遵循地球曲率
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});

核心思想:在弹出窗口中显示信息,通常附加到标记上。

  • 导入库: 通常是基础 maps 库的一部分。
  • 实例化: new google.maps.InfoWindow({ content: 'HTML 内容字符串或 DOM 节点', maxWidth: 200, ariaLabel: '可访问性标签' });。
  • 打开: 调用 infowindow.open({ map: map, anchor: marker }); (现代方式)或 infowindow.open(map, marker); (旧式方式)。
  • 关闭: 调用 infowindow.close();。
  • 常见用法: 在单击标记时打开信息窗口(参见事件章节)。
const infowindow = new google.maps.InfoWindow({
content: '<h3>标记标题</h3><p>关于此地点的一些详细信息。</p>',
ariaLabel: '标记详细信息'
});
marker.addListener('click', () => {
infowindow.open({ anchor: marker, map });
});

核心思想:使用预定义的矢量图标(圆形、箭头)作为标记或在折线上使用。

  • 导入库: 基础 maps 库的一部分 (google.maps.SymbolPath)。
  • 作为标记图标: 将标记的 icon 属性设置为一个 google.maps.Symbol 对象:{ path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW, scale: 5, fillColor: 'red', ... }。
  • 在折线上: 使用 PolylineOptions 的 icons 属性,提供一个 IconSequence 对象数组:[{ icon: symbolObject, offset: '100%', repeat: '50px' }]。
const { Marker } = await google.maps.importLibrary("marker");
const { SymbolPath } = await google.maps.importLibrary("core"); // SymbolPath is in core
// SymbolPath 在 core 库中
const symbolMarker = new Marker({
position: { lat: 45.5231, lng: -122.6765 }, // Portland
map: map,
icon: {
path: SymbolPath.CIRCLE,
scale: 8,
fillColor: '#00F',
fillOpacity: 0.8,
strokeWeight: 1
},
title: '圆形符号'
});

核心思想:响应用户交互(点击、拖动)或地图状态变化(缩放、中心点)。

  • 添加监听器: 在对象(地图、标记等)上使用 addListener 方法:map.addListener('click', (event) => { ... }); 或 marker.addListener('dragend', (event) => { ... });。
  • 事件对象: 处理函数通常接收一个包含相关数据的事件对象(例如,点击事件的 event.latLng)。
  • 常见事件:
  • - `Map`:`click`, `dblclick`, `zoom_changed`, `center_changed`, `bounds_changed`, `idle`。
  • - `Marker`:`click`, `dblclick`, `dragstart`, `drag`, `dragend`。
  • - `InfoWindow`:`closeclick`。
  • 移除监听器: 存储由 addListener 返回的监听器对象,并调用其 remove() 方法:const listener = map.addListener(...); listener.remove();。
map.addListener('click', (mapsMouseEvent) => {
console.log('Map clicked at:', mapsMouseEvent.latLng.toString());
// Example: Place a marker where the user clicked
// 示例:在用户点击的位置放置一个标记
// new google.maps.Marker({ position: mapsMouseEvent.latLng, map: map });
});