Google 地图基础
掌握 HTML5 标准模式与百分比高度继承、HTTPS 与异步脚本加载、center/zoom/mapTypeId 属性配置及多地图实例化,并附离线 Chromium 实测。
学完这一章,你能够
- 掌握 HTML5 标准模式与百分比高度继承、HTTPS 与异步脚本加载、center/zoom/mapTypeId 属性配置及多地图实例化,并附离线 Chromium 实测。
创建首个伦敦地图与 HTML5 标准模式
创建一个基础 Google 地图只需四步:声明 HTML5 文档、引入 Maps API 脚本、准备带明确尺寸的 `<div>` 容器,并在页面加载完成后实例化 `google.maps.Map`。以英国伦敦 `(51.508742, -0.120850)` 为中心、`zoom: 5`、`MapTypeId.ROADMAP` 为例,在离线 Chromium 实测中,`addDomListener(window, 'load', initialize)` 成功于 `500×380` 像素的 `#googleMap` 容器中渲染底图,动态调整 `setZoom(7)` 后缩放级数更新为 `7`。
文档首行必须声明 `<!DOCTYPE html>`,让浏览器进入标准模式(`document.compatMode === "CSS1Compat"`),避免省略 DOCTYPE 后退回混杂模式(Quirks Mode)引发跨浏览器布局差异。在标准模式下,任何使用百分比高度的元素都必须从父级块元素继承明确高度,否则计算结果为 `0px`。本站 Chromium 布局实测直接验证了这一差异:未给父容器设定高度时,`height: 100%` 的子地图容器实测高度为 `0`;而在 `<style>` 中显式声明 `html { height: 100% }`、`body { height: 100%; margin: 0; padding: 0 }` 与 `#googleMap { height: 100% }` 后,在 `900×600` 视口下容器精确撑满 `600px`。
脚本引入、HTTPS 协议与异步动态加载
传统页面通过 `<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">` 引入库文件,将申请到的密钥填入 `key` 参数。早期 v3 文档要求附加 `sensor=true|false` 声明是否使用 GPS 等定位传感器,但现代 Google Maps JavaScript API 已废弃且不再需要 `sensor` 参数;同时无论站点是否强制全站加密,生产环境均应统一使用 HTTPS 加载脚本,避免混合内容拦截。
若不希望地图脚本阻塞首屏呈现,可采用异步加载模式:在 `window.onload` 触发 `loadScript()` 时动态创建 `<script>` 节点插入 `document.body`,并在 URL 末尾附带 `callback=initialize`,待 API 脚本下载解析完毕自动执行初始化回调。本站离线实测解析了 HTTP/HTTPS 脚本地址参数并模拟动态注入 `<script>` 节点,确认回调仅执行 `1` 次且节点标签为 `SCRIPT`。
核心地图选项、容器尺寸与多实例挂载
初始化前需构造 `mapProp` 配置对象,核心包含三个属性:`center` 通过 `new google.maps.LatLng(纬度, 经度)` 指定地图中心;`zoom` 指定缩放级别,`zoom: 0` 表示完整全球缩略视野(在本站 `200px` 宽容器实测中 `zoom=0` 可见经度跨度达 `281.25°`),数值越大视野越精细;`mapTypeId` 指定初始底图类型,支持四种枚举值:`google.maps.MapTypeId.ROADMAP`(常规街道地图)、`SATELLITE`(卫星影像)、`HYBRID`(卫星影像叠加街道与标注透明层)以及 `TERRAIN`(含地形起伏与植被的自然地貌图)。
地图通常挂载于具备固定宽高或已继承百分比高度的 `<div>` 容器(如 `width:500px;height:380px`),通过 `new google.maps.Map(document.getElementById("googleMap"), mapProp)` 创建实例,并配合 `google.maps.event.addDomListener(window, 'load', initialize)`(或现代脚本的 `callback` 参数)确保 DOM 就绪后再执行初始化。同一页面可创建多个互不干扰的 `Map` 对象:本站离线 Chromium 实测在 4 个独立容器中同时实例化 `ROADMAP`、`SATELLITE`、`HYBRID` 与 `TERRAIN` 地图,全部 4 个实例均独立渲染并返回各自预期的 `getMapTypeId()` 值。
实测 HTML5 标准模式百分比高度继承、异步加载与四类型多地图实例
"""Offline Playwright Chromium lab for Google API Ch 03: google-maps-basic."""
import json
from playwright.sync_api import sync_playwright
HTML_MAIN = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Google Maps 基础离线实验</title>
<script>
(function () {
const TILE_SIZE = 256;
function LatLng(lat, lng) { this._lat = Number(lat); this._lng = Number(lng); }
LatLng.prototype.lat = function () { return this._lat; };
LatLng.prototype.lng = function () { return this._lng; };
const MapTypeId = {
ROADMAP: "roadmap",
SATELLITE: "satellite",
HYBRID: "hybrid",
TERRAIN: "terrain",
};
const PALETTE = {
roadmap: "#eef2f7",
satellite: "#1e293b",
hybrid: "#334155",
terrain: "#dcfce7",
};
function Map(container, opts) {
this._div = container;
this._center = opts.center instanceof LatLng ? opts.center : new LatLng(opts.center.lat, opts.center.lng);
this._zoom = Number(opts.zoom);
this._mapTypeId = opts.mapTypeId || MapTypeId.ROADMAP;
const canvas = document.createElement("canvas");
canvas.width = container.clientWidth || 500;
canvas.height = container.clientHeight || 380;
const ctx = canvas.getContext("2d");
ctx.fillStyle = PALETTE[this._mapTypeId] || "#eef2f7";
ctx.fillRect(0, 0, canvas.width, canvas.height);
container.innerHTML = "";
container.appendChild(canvas);
this._canvas = canvas;
}
Map.prototype.getCenter = function () { return this._center; };
Map.prototype.getZoom = function () { return this._zoom; };
Map.prototype.getMapTypeId = function () { return this._mapTypeId; };
Map.prototype.setZoom = function (z) { this._zoom = Number(z); };
Map.prototype.getVisibleLngSpan = function () {
const worldPx = TILE_SIZE * Math.pow(2, this._zoom);
return Math.min(360, Number(((this._canvas.width / worldPx) * 360).toFixed(2)));
};
const event = {
addDomListener(target, eventName, handler) {
target.addEventListener(eventName, handler);
return { target, eventName, handler };
}
};
window.google = { maps: { LatLng, Map, MapTypeId, event } };
})();
window.__maps = {};
function initialize() {
var mapProp = {
center: new google.maps.LatLng(51.508742, -0.120850),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
window.__maps.main = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<div id="multiWrap" style="display:flex;gap:8px;margin-top:8px;">
<div id="googleMap1" style="width:200px;height:150px;"></div>
<div id="googleMap2" style="width:200px;height:150px;"></div>
<div id="googleMap3" style="width:200px;height:150px;"></div>
<div id="googleMap4" style="width:200px;height:150px;"></div>
</div>
</body>
</html>
"""
HTML_PCT = """<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
html { height: 100%; }
body { height: 100%; margin: 0; padding: 0; }
#googleMapPct { height: 100%; }
#collapsedParent { /* no explicit height */ }
#collapsedChild { height: 100%; }
</style>
</head>
<body>
<div id="collapsedParent"><div id="collapsedChild"></div></div>
<div id="googleMapPct"></div>
</body>
</html>
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
try:
page = browser.new_page(viewport={"width": 900, "height": 600})
page.set_content(HTML_MAIN, wait_until="load")
# Case 1: HTML5 standards mode + London basic map + addDomListener
actual_basic = page.evaluate("""() => {
const m = window.__maps.main;
const div = document.getElementById("googleMap");
const rect = div.getBoundingClientRect();
const z5 = m.getZoom();
m.setZoom(7);
const z7 = m.getZoom();
return {
compat_mode: document.compatMode,
div_width: rect.width,
div_height: rect.height,
lat: Number(m.getCenter().lat().toFixed(6)),
lng: Number(m.getCenter().lng().toFixed(6)),
initial_zoom: z5,
updated_zoom: z7,
map_type: m.getMapTypeId()
};
}""")
expected_basic = {
"compat_mode": "CSS1Compat",
"div_width": 500,
"div_height": 380,
"lat": 51.508742,
"lng": -0.12085,
"initial_zoom": 5,
"updated_zoom": 7,
"map_type": "roadmap",
}
cases.append({
"name": "london_map_basic_and_doctype",
"passed": actual_basic == expected_basic,
"expected": expected_basic,
"actual": actual_basic,
})
# Case 2: Four simultaneous map instances with all 4 MapTypeId values + zoom=0 world span
actual_four = page.evaluate("""() => {
const c = new google.maps.LatLng(51.508742, -0.120850);
const ids = [
["googleMap1", google.maps.MapTypeId.ROADMAP, 5],
["googleMap2", google.maps.MapTypeId.SATELLITE, 5],
["googleMap3", google.maps.MapTypeId.HYBRID, 5],
["googleMap4", google.maps.MapTypeId.TERRAIN, 0],
];
const types = [];
let zoom0Span = 0;
for (const [id, mt, z] of ids) {
const inst = new google.maps.Map(document.getElementById(id), { center: c, zoom: z, mapTypeId: mt });
types.push(inst.getMapTypeId());
if (z === 0) zoom0Span = inst.getVisibleLngSpan();
}
return {
instance_count: types.length,
map_types: types,
zoom0_lng_span: zoom0Span
};
}""")
expected_four = {
"instance_count": 4,
"map_types": ["roadmap", "satellite", "hybrid", "terrain"],
"zoom0_lng_span": 281.25,
}
cases.append({
"name": "four_map_instances_all_types",
"passed": actual_four == expected_four,
"expected": expected_four,
"actual": actual_four,
})
# Case 3: HTTP vs HTTPS URL parsing & async loadScript(callback=initialize)
actual_loader = page.evaluate("""() => {
const httpUrl = new URL("http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false");
const httpsUrl = new URL("https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false&callback=initialize");
let asyncCalls = 0;
window.__asyncInitialize = function () { asyncCalls += 1; };
// Offline dynamic script creation mirroring loadScript() without hitting external network
const script = document.createElement("script");
script.type = "text/javascript";
script.dataset.requestedSrc = httpsUrl.toString();
script.textContent = "window.__asyncInitialize();";
document.body.appendChild(script);
return {
http_protocol: httpUrl.protocol,
https_protocol: httpsUrl.protocol,
sensor_param: httpsUrl.searchParams.get("sensor"),
callback_param: httpsUrl.searchParams.get("callback"),
appended_tag: script.tagName,
callback_executed_count: asyncCalls
};
}""")
expected_loader = {
"http_protocol": "http:",
"https_protocol": "https:",
"sensor_param": "false",
"callback_param": "initialize",
"appended_tag": "SCRIPT",
"callback_executed_count": 1,
}
cases.append({
"name": "script_loader_https_and_async_callback",
"passed": actual_loader == expected_loader,
"expected": expected_loader,
"actual": actual_loader,
})
# Case 4: Percentage height inheritance in HTML5 standards mode
page.set_content(HTML_PCT, wait_until="load")
actual_pct = page.evaluate("""() => {
const collapsed = document.getElementById("collapsedChild").getBoundingClientRect().height;
const full = document.getElementById("googleMapPct").getBoundingClientRect().height;
return {
compat_mode: document.compatMode,
without_parent_height: collapsed,
with_html_body_100pct: full
};
}""")
expected_pct = {
"compat_mode": "CSS1Compat",
"without_parent_height": 0,
"with_html_body_100pct": 600,
}
cases.append({
"name": "percentage_height_inheritance",
"passed": actual_pct == expected_pct,
"expected": expected_pct,
"actual": actual_pct,
})
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 CSS1Compat 标准模式下未设父高的 100% 容器坍缩为 0px 而 html/body 100% 撑满 600px;伦敦基础地图 500×380 正常初始化并缩放至 7;四地图实例分别返回 roadmap/satellite/hybrid/terrain。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:72cd24316edbd0be727a95b1f964962be5545515915107d021cff3993da5f66c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ccb6c14a821cb9399b34d5f7c585e605bdebd8c56cbfebdc930c54bf5ccac493
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为何在 HTML5 标准模式下仅给 #googleMap 设置 height: 100% 会导致地图空白不可见?
展开参考解答
标准模式下百分比高度依赖父元素显式高度,若 html 与 body 未设定 height: 100%,父级高度为 auto,计算出的地图容器高度会坍缩为 0px,导致画布无法显示。