"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/googleapi-google-maps-basic-lab/explore-google-maps-basic.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-google-maps-basic.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联9章) · 含当前章节或实例 · mbskycom202612a1029.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1031.zip