蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 实测控件显隐切换、样式定位配置与自定义 Home 按钮点击回中

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-google-maps-controls.py
explore-google-maps-controls.py296 行
"""Offline Playwright Chromium lab for Google API Ch 06: google-maps-controls."""
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 控件集离线实验</title>
<style>
  body { margin: 0; font-family: sans-serif; }
  #googleMap { width: 520px; height: 380px; position: relative; border: 1px solid #94a3b8; background: #e2e8f0; overflow: hidden; }
  .gm-ctrl-slot { position: absolute; display: flex; gap: 4px; z-index: 5; }
  .gm-ctrl-slot[data-pos="TOP_LEFT"] { top: 6px; left: 6px; }
  .gm-ctrl-slot[data-pos="TOP_CENTER"] { top: 6px; left: 50%; transform: translateX(-50%); }
  .gm-ctrl-slot[data-pos="TOP_RIGHT"] { top: 6px; right: 6px; }
  .gm-ctrl-slot[data-pos="BOTTOM_RIGHT"] { bottom: 6px; right: 6px; }
  .gm-ctrl { background: #fff; border: 1px solid #64748b; padding: 2px 6px; font-size: 11px; }
</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 ZoomControlStyle = { DEFAULT: 0, SMALL: 1, LARGE: 2 };
  const MapTypeControlStyle = { DEFAULT: 0, HORIZONTAL_BAR: 1, DROPDOWN_MENU: 2 };
  const ControlPosition = {
    TOP_LEFT: 1, TOP_CENTER: 2, TOP_RIGHT: 3,
    LEFT_CENTER: 4, LEFT_TOP: 5, LEFT_BOTTOM: 6,
    RIGHT_TOP: 7, RIGHT_CENTER: 8, RIGHT_BOTTOM: 9,
    BOTTOM_LEFT: 10, BOTTOM_CENTER: 11, BOTTOM_RIGHT: 12
  };
  const POS_NAMES = Object.fromEntries(Object.entries(ControlPosition).map(([k, v]) => [v, k]));

  function MVCArray(slotEl) {
    this._items = [];
    this._slot = slotEl;
  }
  MVCArray.prototype.push = function (node) {
    this._items.push(node);
    this._slot.appendChild(node);
    return this._items.length;
  };
  MVCArray.prototype.getLength = function () { return this._items.length; };

  const ALL_CONTROLS = [
    "zoomControl", "panControl", "mapTypeControl", "streetViewControl",
    "scaleControl", "rotateControl", "overviewMapControl"
  ];
  const DEFAULT_ON = new Set(["zoomControl", "panControl", "mapTypeControl", "streetViewControl"]);

  function Map(div, opts) {
    this._div = div;
    this._center = opts.center;
    this._zoom = opts.zoom || 5;
    this._opts = {};
    this._slots = {};
    this.controls = {};
    div.innerHTML = "";
    for (const [name, code] of Object.entries(ControlPosition)) {
      const slot = document.createElement("div");
      slot.className = "gm-ctrl-slot";
      slot.dataset.pos = name;
      div.appendChild(slot);
      this._slots[code] = slot;
      this.controls[code] = new MVCArray(slot);
    }
    this._builtinLayer = document.createElement("div");
    this._builtinLayer.className = "gm-builtin-controls";
    div.appendChild(this._builtinLayer);
    this.setOptions(opts);
  }
  Map.prototype.getCenter = function () { return this._center; };
  Map.prototype.setCenter = function (ll) { this._center = ll; };
  Map.prototype.setOptions = function (opts) {
    Object.assign(this._opts, opts);
    this._renderControls();
  };
  Map.prototype._isEnabled = function (name) {
    if (typeof this._opts[name] === "boolean") return this._opts[name];
    if (this._opts.disableDefaultUI) return false;
    return DEFAULT_ON.has(name);
  };
  Map.prototype.getVisibleControls = function () {
    return ALL_CONTROLS.filter(c => this._isEnabled(c));
  };
  Map.prototype._renderControls = function () {
    this._builtinLayer.innerHTML = "";
    for (const name of this.getVisibleControls()) {
      const el = document.createElement("div");
      el.className = "gm-ctrl";
      el.dataset.control = name;
      if (name === "zoomControl") {
        const st = (this._opts.zoomControlOptions && this._opts.zoomControlOptions.style) ?? ZoomControlStyle.DEFAULT;
        el.dataset.style = Object.keys(ZoomControlStyle).find(k => ZoomControlStyle[k] === st);
      }
      if (name === "mapTypeControl") {
        const mto = this._opts.mapTypeControlOptions || {};
        const st = mto.style ?? MapTypeControlStyle.DEFAULT;
        const pos = mto.position ?? ControlPosition.TOP_RIGHT;
        el.dataset.style = Object.keys(MapTypeControlStyle).find(k => MapTypeControlStyle[k] === st);
        el.dataset.position = POS_NAMES[pos];
      }
      el.textContent = name;
      this._builtinLayer.appendChild(el);
    }
  };

  const event = {
    addDomListener(node, evName, fn) {
      node.addEventListener(evName, fn);
      return { node, evName, fn };
    }
  };

  window.google = { maps: { LatLng, Map, ZoomControlStyle, MapTypeControlStyle, ControlPosition, 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: Default controls vs disableDefaultUI:true vs enabling all 7 controls
            actual_toggle = page.evaluate("""() => {
                const london = new google.maps.LatLng(51.508742, -0.120850);
                window.__london = london;
                const m1 = new google.maps.Map(document.getElementById("googleMap"), { center: london, zoom: 5 });
                const defaultVisible = m1.getVisibleControls();
                const m2 = new google.maps.Map(document.getElementById("googleMap"), { center: london, zoom: 5, disableDefaultUI: true });
                const disabledVisible = m2.getVisibleControls();
                m2.setOptions({
                    panControl: true, zoomControl: true, mapTypeControl: true,
                    scaleControl: true, streetViewControl: true,
                    overviewMapControl: true, rotateControl: true
                });
                const allVisible = m2.getVisibleControls();
                window.__map = m2;
                return {
                    default_controls: defaultVisible,
                    disabled_count: disabledVisible.length,
                    all_enabled_count: allVisible.length,
                    has_scale_rotate_overview: allVisible.includes("scaleControl") && allVisible.includes("rotateControl") && allVisible.includes("overviewMapControl")
                };
            }""")
            expected_toggle = {
                "default_controls": ["zoomControl", "panControl", "mapTypeControl", "streetViewControl"],
                "disabled_count": 0,
                "all_enabled_count": 7,
                "has_scale_rotate_overview": True,
            }
            cases.append({
                "name": "default_and_disabled_ui_controls",
                "passed": actual_toggle == expected_toggle,
                "expected": expected_toggle,
                "actual": actual_toggle,
            })

            # Case 2: zoomControlOptions requires zoomControl:true; test SMALL/LARGE/DEFAULT
            actual_zoom_ctrl = page.evaluate("""() => {
                const m = window.__map;
                m.setOptions({ zoomControl: false, zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL } });
                const hiddenWhenFalse = !document.querySelector('[data-control="zoomControl"]');
                m.setOptions({ zoomControl: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL } });
                const styleSmall = document.querySelector('[data-control="zoomControl"]').dataset.style;
                m.setOptions({ zoomControlOptions: { style: google.maps.ZoomControlStyle.LARGE } });
                const styleLarge = document.querySelector('[data-control="zoomControl"]').dataset.style;
                return {
                    hidden_when_disabled: hiddenWhenFalse,
                    small_style: styleSmall,
                    large_style: styleLarge
                };
            }""")
            expected_zoom_ctrl = {
                "hidden_when_disabled": True,
                "small_style": "SMALL",
                "large_style": "LARGE",
            }
            cases.append({
                "name": "zoom_control_style_options",
                "passed": actual_zoom_ctrl == expected_zoom_ctrl,
                "expected": expected_zoom_ctrl,
                "actual": actual_zoom_ctrl,
            })

            # Case 3: mapTypeControlOptions DROPDOWN_MENU + ControlPosition.TOP_CENTER
            actual_mt = page.evaluate("""() => {
                const m = window.__map;
                m.setOptions({
                    mapTypeControl: true,
                    mapTypeControlOptions: {
                        style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
                        position: google.maps.ControlPosition.TOP_CENTER
                    }
                });
                const el = document.querySelector('[data-control="mapTypeControl"]');
                return {
                    style: el.dataset.style,
                    position: el.dataset.position,
                    enum_horizontal: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                    enum_dropdown: google.maps.MapTypeControlStyle.DROPDOWN_MENU
                };
            }""")
            expected_mt = {
                "style": "DROPDOWN_MENU",
                "position": "TOP_CENTER",
                "enum_horizontal": 1,
                "enum_dropdown": 2,
            }
            cases.append({
                "name": "maptype_control_style_and_position",
                "passed": actual_mt == expected_mt,
                "expected": expected_mt,
                "actual": actual_mt,
            })

            # Case 4: Custom Home control DOM attached & clicked in Chromium to recenter London
            page.evaluate("""() => {
                const controlDiv = document.createElement("div");
                controlDiv.style.padding = "5px";
                const controlUI = document.createElement("div");
                controlUI.id = "customHomeBtn";
                controlUI.style.backgroundColor = "yellow";
                controlUI.style.border = "1px solid";
                controlUI.style.cursor = "pointer";
                controlUI.style.textAlign = "center";
                controlUI.title = "Set map to London";
                controlDiv.appendChild(controlUI);
                const controlText = document.createElement("div");
                controlText.style.fontFamily = "Arial,sans-serif";
                controlText.style.fontSize = "12px";
                controlText.style.paddingLeft = "4px";
                controlText.style.paddingRight = "4px";
                controlText.innerHTML = "<b>Home</b>";
                controlUI.appendChild(controlText);

                google.maps.event.addDomListener(controlUI, "click", function () {
                    window.__map.setCenter(window.__london);
                });
                window.__map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controlDiv);
                window.__map.setCenter(new google.maps.LatLng(48.8566, 2.3522));
            }""")
            before_click = page.evaluate("() => [window.__map.getCenter().lat(), window.__map.getCenter().lng()]")
            page.locator("#customHomeBtn").click()
            actual_home = page.evaluate("""(before) => ({
                before_lat: before[0],
                before_lng: before[1],
                after_lat: Number(window.__map.getCenter().lat().toFixed(6)),
                after_lng: Number(window.__map.getCenter().lng().toFixed(6)),
                button_text: document.getElementById("customHomeBtn").textContent.trim(),
                button_bg: document.getElementById("customHomeBtn").style.backgroundColor,
                slot_length: window.__map.controls[google.maps.ControlPosition.TOP_RIGHT].getLength()
            })""", before_click)
            expected_home = {
                "before_lat": 48.8566,
                "before_lng": 2.3522,
                "after_lat": 51.508742,
                "after_lng": -0.12085,
                "button_text": "Home",
                "button_bg": "yellow",
                "slot_length": 1,
            }
            cases.append({
                "name": "custom_home_control_recenter",
                "passed": actual_home == expected_home,
                "expected": expected_home,
                "actual": actual_home,
            })
        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-controls-lab/explore-google-maps-controls.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-google-maps-controls.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Google 地图

课程关联工程包(登记关联9章) · 含当前章节或实例 · mbskycom202612a1029.zip

下载课程关联工程包:Google 地图

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1032.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习