"""Offline Playwright Chromium lab for Google API Ch 07: google-maps-types."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>Google Maps 地图类型与 45° 图像离线实验</title>
<style>
body { margin: 0; font-family: sans-serif; }
#googleMap { width: 500px; height: 380px; position: relative; border: 1px solid #94a3b8; }
</style>
</head>
<body>
<div id="googleMap"></div>
<script>
(function () {
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 TYPE_BG = {
roadmap: "#f1f5f9",
satellite: "#0f172a",
hybrid: "#1e293b",
terrain: "#d1fae5",
};
const event = {
addListener(inst, name, fn) {
inst._listeners[name] = inst._listeners[name] || [];
inst._listeners[name].push(fn);
return { inst, name, fn };
},
trigger(inst, name) {
for (const fn of (inst._listeners[name] || [])) fn();
}
};
function Map(div, opts) {
this._div = div;
this._center = opts.center;
this._zoom = opts.zoom;
this._mapTypeId = opts.mapTypeId || MapTypeId.ROADMAP;
this._heading = 0;
this._tiltDisabled = false;
this._listeners = {};
this._canvas = document.createElement("canvas");
this._canvas.width = div.clientWidth || 500;
this._canvas.height = div.clientHeight || 380;
div.innerHTML = "";
div.appendChild(this._canvas);
this._tilt = this._supports45() ? 45 : 0;
this._render();
}
Map.prototype._supports45 = function () {
const typeOk = this._mapTypeId === MapTypeId.SATELLITE || this._mapTypeId === MapTypeId.HYBRID;
const inVenice = Math.abs(this._center.lat() - 45.434046) < 0.1 && Math.abs(this._center.lng() - 12.340284) < 0.1;
return typeOk && inVenice && this._zoom >= 18;
};
Map.prototype._syncTilt = function () {
const next = (!this._tiltDisabled && this._supports45()) ? 45 : 0;
if (next !== this._tilt) {
this._tilt = next;
event.trigger(this, "tilt_changed");
}
};
Map.prototype.getMapTypeId = function () { return this._mapTypeId; };
Map.prototype.setMapTypeId = function (mt) {
this._mapTypeId = mt;
event.trigger(this, "maptypeid_changed");
this._syncTilt();
this._render();
};
Map.prototype.getZoom = function () { return this._zoom; };
Map.prototype.setZoom = function (z) {
this._zoom = Number(z);
this._syncTilt();
this._render();
};
Map.prototype.getTilt = function () { return this._tilt; };
Map.prototype.setTilt = function (deg) {
if (deg === 0) {
this._tiltDisabled = true;
this._syncTilt();
} else if (deg === 45) {
this._tiltDisabled = false;
this._syncTilt();
}
this._render();
};
Map.prototype.getHeading = function () { return this._heading; };
Map.prototype.rotateClockwise90 = function () {
if (this._tilt === 45) {
this._heading = (this._heading + 90) % 360;
event.trigger(this, "heading_changed");
}
};
Map.prototype.has45Controls = function () {
return this._tilt === 45;
};
Map.prototype._render = function () {
const ctx = this._canvas.getContext("2d");
ctx.fillStyle = TYPE_BG[this._mapTypeId] || "#ffffff";
ctx.fillRect(0, 0, this._canvas.width, this._canvas.height);
};
window.google = { maps: { LatLng, Map, MapTypeId, event } };
})();
</script>
</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": 800, "height": 600})
page.set_content(HTML_DOC, wait_until="load")
# Case 1: 4 basic MapTypeId values & dynamic setMapTypeId()
actual_types = page.evaluate("""() => {
const london = new google.maps.LatLng(51.508742, -0.120850);
const map = new google.maps.Map(document.getElementById("googleMap"), {
center: london, zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP
});
const changes = [];
google.maps.event.addListener(map, "maptypeid_changed", () => changes.push(map.getMapTypeId()));
const sampleRgb = () => Array.from(map._canvas.getContext("2d").getImageData(10, 10, 1, 1).data).slice(0, 3);
const rgbRoadmap = sampleRgb();
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
const rgbHybrid = sampleRgb();
map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
return {
enum_values: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
dynamic_changes: changes,
distinct_canvas_rgb: JSON.stringify(rgbRoadmap) !== JSON.stringify(rgbHybrid)
};
}""")
expected_types = {
"enum_values": ["roadmap", "satellite", "hybrid", "terrain"],
"dynamic_changes": ["hybrid", "satellite", "terrain"],
"distinct_canvas_rgb": True,
}
cases.append({
"name": "basic_map_types_and_dynamic_switch",
"passed": actual_types == expected_types,
"expected": expected_types,
"actual": actual_types,
})
# Case 2: 45-degree imagery at Venice Doge's Palace (zoom 18 HYBRID) + clockwise rotate + zoom-out revert
actual_45 = page.evaluate("""() => {
const venice = new google.maps.LatLng(45.434046, 12.340284);
const map = new google.maps.Map(document.getElementById("googleMap"), {
center: venice, zoom: 18, mapTypeId: google.maps.MapTypeId.HYBRID
});
window.__veniceMap = map;
const initialTilt = map.getTilt();
const initialHeading = map.getHeading();
const controlsAt18 = map.has45Controls();
const headings = [initialHeading];
for (let i = 0; i < 4; i++) {
map.rotateClockwise90();
headings.push(map.getHeading());
}
map.setZoom(14);
const tiltAfterZoomOut = map.getTilt();
const controlsAt14 = map.has45Controls();
map.setZoom(18);
return {
initial_tilt: initialTilt,
controls_visible_at_z18: controlsAt18,
clockwise_headings: headings,
tilt_after_zoom_out: tiltAfterZoomOut,
controls_visible_at_z14: controlsAt14,
restored_tilt_at_z18: map.getTilt()
};
}""")
expected_45 = {
"initial_tilt": 45,
"controls_visible_at_z18": True,
"clockwise_headings": [0, 90, 180, 270, 0],
"tilt_after_zoom_out": 0,
"controls_visible_at_z14": False,
"restored_tilt_at_z18": 45,
}
cases.append({
"name": "imagery_45_degree_high_zoom_behavior",
"passed": actual_45 == expected_45,
"expected": expected_45,
"actual": actual_45,
})
# Case 3: setTilt(0) and setTilt(45) + ROADMAP non-support check
actual_tilt = page.evaluate("""() => {
const map = window.__veniceMap;
const tiltEvents = [];
google.maps.event.addListener(map, "tilt_changed", () => tiltEvents.push(map.getTilt()));
map.setTilt(0);
const afterDisable = map.getTilt();
map.setTilt(45);
const afterEnable = map.getTilt();
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
const onRoadmap = map.getTilt();
return {
after_set_tilt_0: afterDisable,
after_set_tilt_45: afterEnable,
on_roadmap_tilt: onRoadmap,
tilt_event_sequence: tiltEvents
};
}""")
expected_tilt = {
"after_set_tilt_0": 0,
"after_set_tilt_45": 45,
"on_roadmap_tilt": 0,
"tilt_event_sequence": [0, 45, 0],
}
cases.append({
"name": "set_tilt_toggle_0_and_45",
"passed": actual_tilt == expected_tilt,
"expected": expected_tilt,
"actual": actual_tilt,
})
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-types-lab/explore-google-maps-types.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-google-maps-types.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联9章) · 含当前章节或实例 · mbskycom202612a1029.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1036.zip