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

离线 Chromium 全量实测 Map() 构造器、20 个方法、3 个属性与 19 个事件

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-ref-map.py
explore-ref-map.py387 行
"""Offline Playwright Chromium lab for Google API Ch 09: ref-map."""
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 Map() 构造器完整契约离线实验</title>
<style>
  body { margin: 0; font-family: sans-serif; }
  #googleMap { width: 512px; height: 256px; position: relative; border: 1px solid #94a3b8; background: #e2e8f0; }
</style>
</head>
<body>
<div id="googleMap"></div>
<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; };

  function LatLngBounds(sw, ne) { this._sw = sw; this._ne = ne; }
  LatLngBounds.prototype.getSouthWest = function () { return this._sw; };
  LatLngBounds.prototype.getNorthEast = function () { return this._ne; };
  LatLngBounds.prototype.getCenter = function () {
    return new LatLng((this._sw.lat() + this._ne.lat()) / 2, (this._sw.lng() + this._ne.lng()) / 2);
  };

  function Point(x, y) { this.x = x; this.y = y; }

  const MercatorProjection = {
    fromLatLngToPoint(ll) {
      let siny = Math.sin((ll.lat() * Math.PI) / 180);
      siny = Math.min(Math.max(siny, -0.9999), 0.9999);
      return new Point(
        TILE_SIZE * (0.5 + ll.lng() / 360),
        TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI))
      );
    },
    fromPointToLatLng(pt) {
      const lng = (pt.x / TILE_SIZE - 0.5) * 360;
      const latRad = 2 * Math.atan(Math.exp((0.5 - pt.y / TILE_SIZE) * 2 * Math.PI)) - Math.PI / 2;
      return new LatLng((latRad * 180) / Math.PI, lng);
    }
  };

  function MVCArray() { this._arr = []; }
  MVCArray.prototype.push = function (item) { this._arr.push(item); return this._arr.length; };
  MVCArray.prototype.getLength = function () { return this._arr.length; };

  function MapTypeRegistry() { this._map = {}; }
  MapTypeRegistry.prototype.set = function (id, mt) { this._map[id] = mt; };
  MapTypeRegistry.prototype.get = function (id) { return this._map[id]; };

  function StreetViewPanorama(opts) { this.position = (opts && opts.position) || null; this.visible = Boolean(opts && opts.visible); }

  const MapTypeId = { ROADMAP: "roadmap", SATELLITE: "satellite", HYBRID: "hybrid", TERRAIN: "terrain" };
  const ControlPosition = { TOP_LEFT: 1, TOP_RIGHT: 3, BOTTOM_RIGHT: 12 };

  const event = {
    addListener(inst, name, fn) {
      inst._listeners[name] = inst._listeners[name] || [];
      inst._listeners[name].push(fn);
      return { inst, name, fn };
    },
    trigger(inst, name, payload) {
      for (const fn of (inst._listeners[name] || [])) fn(payload);
    }
  };

  function Map(div, opts) {
    this._div = div;
    this._center = opts.center || new LatLng(0, 0);
    this._zoom = typeof opts.zoom === "number" ? opts.zoom : 4;
    this._mapTypeId = opts.mapTypeId || MapTypeId.ROADMAP;
    this._heading = 0;
    this._tilt = 0;
    this._projection = MercatorProjection;
    this._streetView = new StreetViewPanorama({ position: this._center, visible: false });
    this._listeners = {};
    this.controls = {
      [ControlPosition.TOP_LEFT]: new MVCArray(),
      [ControlPosition.TOP_RIGHT]: new MVCArray(),
      [ControlPosition.BOTTOM_RIGHT]: new MVCArray(),
    };
    this.mapTypes = new MapTypeRegistry();
    this.overlayMapTypes = new MVCArray();

    const makeMouse = (e) => {
      const r = div.getBoundingClientRect();
      const px = e.clientX - r.left, py = e.clientY - r.top;
      const scale = Math.pow(2, this._zoom);
      const cp = this._projection.fromLatLngToPoint(this._center);
      const ll = this._projection.fromPointToLatLng(new Point(cp.x + (px - div.clientWidth / 2) / scale, cp.y + (py - div.clientHeight / 2) / scale));
      return { latLng: ll };
    };
    div.addEventListener("click", (e) => event.trigger(this, "click", makeMouse(e)));
    div.addEventListener("dblclick", (e) => event.trigger(this, "dblclick", makeMouse(e)));
    div.addEventListener("contextmenu", (e) => { e.preventDefault(); event.trigger(this, "rightclick", makeMouse(e)); });
    div.addEventListener("mouseover", (e) => event.trigger(this, "mouseover", makeMouse(e)));
    div.addEventListener("mousemove", (e) => event.trigger(this, "mousemove", makeMouse(e)));
    div.addEventListener("mouseout", (e) => event.trigger(this, "mouseout", makeMouse(e)));
  }

  Map.prototype.getDiv = function () { return this._div; };
  Map.prototype.getCenter = function () { return this._center; };
  Map.prototype.getZoom = function () { return this._zoom; };
  Map.prototype.getMapTypeId = function () { return this._mapTypeId; };
  Map.prototype.getHeading = function () { return this._heading; };
  Map.prototype.getTilt = function () { return this._tilt; };
  Map.prototype.getProjection = function () { return this._projection; };
  Map.prototype.getStreetView = function () { return this._streetView; };
  Map.prototype.setStreetView = function (sv) { this._streetView = sv; };
  Map.prototype.getBounds = function () {
    const scale = Math.pow(2, this._zoom);
    const cp = this._projection.fromLatLngToPoint(this._center);
    const halfW = (this._div.clientWidth / 2) / scale;
    const halfH = (this._div.clientHeight / 2) / scale;
    const sw = this._projection.fromPointToLatLng(new Point(cp.x - halfW, cp.y + halfH));
    const ne = this._projection.fromPointToLatLng(new Point(cp.x + halfW, cp.y - halfH));
    return new LatLngBounds(sw, ne);
  };
  Map.prototype.setCenter = function (ll) {
    this._center = ll;
    event.trigger(this, "center_changed");
    event.trigger(this, "bounds_changed");
  };
  Map.prototype.panTo = function (ll) {
    this.setCenter(ll);
    event.trigger(this, "idle");
  };
  Map.prototype.panBy = function (dx, dy) {
    const scale = Math.pow(2, this._zoom);
    const cp = this._projection.fromLatLngToPoint(this._center);
    const next = this._projection.fromPointToLatLng(new Point(cp.x + dx / scale, cp.y + dy / scale));
    this.panTo(next);
  };
  Map.prototype.setZoom = function (z) {
    this._zoom = Number(z);
    event.trigger(this, "zoom_changed");
    event.trigger(this, "bounds_changed");
  };
  Map.prototype.fitBounds = function (bounds) {
    this._center = bounds.getCenter();
    const spanLng = Math.abs(bounds.getNorthEast().lng() - bounds.getSouthWest().lng());
    const z = Math.max(0, Math.min(18, Math.floor(Math.log2(360 / Math.max(spanLng, 0.01)))));
    this._zoom = z;
    event.trigger(this, "center_changed");
    event.trigger(this, "zoom_changed");
    event.trigger(this, "bounds_changed");
  };
  Map.prototype.panToBounds = function (bounds) {
    this.panTo(bounds.getCenter());
  };
  Map.prototype.setMapTypeId = function (mt) {
    this._mapTypeId = mt;
    event.trigger(this, "maptypeid_changed");
    event.trigger(this, "projection_changed");
    event.trigger(this, "tilesloaded");
  };
  Map.prototype.setHeading = function (h) {
    this._heading = Number(h);
    event.trigger(this, "heading_changed");
  };
  Map.prototype.setTilt = function (t) {
    this._tilt = Number(t);
    event.trigger(this, "tilt_changed");
  };
  Map.prototype.setOptions = function (opts) {
    if (opts.center) this.setCenter(opts.center);
    if (typeof opts.zoom === "number") this.setZoom(opts.zoom);
    if (opts.mapTypeId) this.setMapTypeId(opts.mapTypeId);
  };

  window.google = {
    maps: { LatLng, LatLngBounds, Point, Map, MapTypeId, ControlPosition, StreetViewPanorama, 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: Map(HTMLElement, MapOptions) constructor & getters
            actual_get = page.evaluate("""() => {
                const mapOpt = {
                    center: new google.maps.LatLng(51.508742, -0.120850),
                    zoom: 5,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                window.__map = new google.maps.Map(document.getElementById("googleMap"), mapOpt);
                const m = window.__map;
                const b = m.getBounds();
                const projPt = m.getProjection().fromLatLngToPoint(new google.maps.LatLng(0, 0));
                const customSv = new google.maps.StreetViewPanorama({ position: m.getCenter(), visible: true });
                m.setStreetView(customSv);
                return {
                    div_id: m.getDiv().id,
                    center_lat: Number(m.getCenter().lat().toFixed(6)),
                    zoom: m.getZoom(),
                    map_type: m.getMapTypeId(),
                    bounds_ordered: b.getSouthWest().lat() < b.getNorthEast().lat() && b.getSouthWest().lng() < b.getNorthEast().lng(),
                    equator_world_point: [projPt.x, projPt.y],
                    street_view_visible: m.getStreetView().visible
                };
            }""")
            expected_get = {
                "div_id": "googleMap",
                "center_lat": 51.508742,
                "zoom": 5,
                "map_type": "roadmap",
                "bounds_ordered": True,
                "equator_world_point": [128, 128],
                "street_view_visible": True,
            }
            cases.append({
                "name": "map_constructor_and_getters",
                "passed": actual_get == expected_get,
                "expected": expected_get,
                "actual": actual_get,
            })

            # Case 2: Viewport & aerial mutators (setCenter/panTo/panBy/fitBounds/panToBounds/setOptions/setTilt/setHeading)
            actual_mut = page.evaluate("""() => {
                const m = window.__map;
                m.setOptions({ zoom: 6, mapTypeId: google.maps.MapTypeId.HYBRID });
                m.setTilt(45);
                m.setHeading(90);
                m.panTo(new google.maps.LatLng(45.434, 12.340));
                const lngBeforePanBy = m.getCenter().lng();
                m.panBy(64, 0);
                const lngAfterPanBy = m.getCenter().lng();
                const euBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(48.0, -2.0),
                    new google.maps.LatLng(54.0, 6.0)
                );
                m.fitBounds(euBounds);
                const fitZoom = m.getZoom();
                const fitLat = Number(m.getCenter().lat().toFixed(2));
                m.panToBounds(new google.maps.LatLngBounds(
                    new google.maps.LatLng(50.0, 0.0),
                    new google.maps.LatLng(52.0, 2.0)
                ));
                return {
                    map_type: m.getMapTypeId(),
                    tilt: m.getTilt(),
                    heading: m.getHeading(),
                    pan_by_east_moved: lngAfterPanBy > lngBeforePanBy,
                    fit_bounds_zoom: fitZoom,
                    fit_bounds_center_lat: fitLat,
                    pan_to_bounds_center: [Number(m.getCenter().lat().toFixed(2)), Number(m.getCenter().lng().toFixed(2))]
                };
            }""")
            expected_mut = {
                "map_type": "hybrid",
                "tilt": 45,
                "heading": 90,
                "pan_by_east_moved": True,
                "fit_bounds_zoom": 5,
                "fit_bounds_center_lat": 51.0,
                "pan_to_bounds_center": [51.0, 1.0],
            }
            cases.append({
                "name": "map_viewport_and_aerial_mutators",
                "passed": actual_mut == expected_mut,
                "expected": expected_mut,
                "actual": actual_mut,
            })

            # Case 3: Properties controls, mapTypes, overlayMapTypes
            actual_props = page.evaluate("""() => {
                const m = window.__map;
                const badge = document.createElement("button");
                badge.textContent = "Reset";
                m.controls[google.maps.ControlPosition.TOP_LEFT].push(badge);
                m.mapTypes.set("night_grid", { name: "Night Grid", maxZoom: 18 });
                m.overlayMapTypes.push({ name: "Weather Radar" });
                return {
                    controls_top_left_len: m.controls[google.maps.ControlPosition.TOP_LEFT].getLength(),
                    registered_map_type_name: m.mapTypes.get("night_grid").name,
                    overlay_map_types_len: m.overlayMapTypes.getLength()
                };
            }""")
            expected_props = {
                "controls_top_left_len": 1,
                "registered_map_type_name": "Night Grid",
                "overlay_map_types_len": 1,
            }
            cases.append({
                "name": "map_properties_controls_and_registries",
                "passed": actual_props == expected_props,
                "expected": expected_props,
                "actual": actual_props,
            })

            # Case 4: All 19 documented Map events lifecycle
            page.evaluate("""() => {
                const m = window.__map;
                window.__events = [];
                window.__mouseHasLatLng = {};
                const ALL_19 = [
                    "bounds_changed", "center_changed", "click", "dblclick",
                    "drag", "dragend", "dragstart", "heading_changed", "idle",
                    "maptypeid_changed", "mousemove", "mouseout", "mouseover",
                    "projection_changed", "resize", "rightclick", "tilesloaded",
                    "tilt_changed", "zoom_changed"
                ];
                for (const evName of ALL_19) {
                    google.maps.event.addListener(m, evName, (payload) => {
                        if (!window.__events.includes(evName)) window.__events.push(evName);
                        if (payload && payload.latLng) {
                            window.__mouseHasLatLng[evName] = typeof payload.latLng.lat() === "number";
                        }
                    });
                }
                m.setCenter(new google.maps.LatLng(51.5, -0.12));
                m.setZoom(7);
                m.panTo(new google.maps.LatLng(51.6, -0.1));
                m.setMapTypeId(google.maps.MapTypeId.SATELLITE);
                m.setHeading(180);
                m.setTilt(0);
                google.maps.event.trigger(m, "dragstart");
                google.maps.event.trigger(m, "drag");
                google.maps.event.trigger(m, "dragend");
                google.maps.event.trigger(m, "resize");
            }""")
            box = page.locator("#googleMap").bounding_box()
            cx, cy = box["x"] + 150, box["y"] + 100
            page.mouse.move(cx, cy)
            page.mouse.move(cx + 15, cy + 10)
            page.mouse.click(cx + 15, cy + 10)
            page.mouse.dblclick(cx + 15, cy + 10)
            page.mouse.click(cx + 15, cy + 10, button="right")
            page.mouse.move(box["x"] + box["width"] + 40, box["y"] + 10)

            actual_ev = page.evaluate("""() => ({
                fired_count: window.__events.length,
                fired_sorted: window.__events.slice().sort(),
                mouse_events_with_latlng: Object.keys(window.__mouseHasLatLng).sort()
            })""")
            expected_ev = {
                "fired_count": 19,
                "fired_sorted": [
                    "bounds_changed", "center_changed", "click", "dblclick",
                    "drag", "dragend", "dragstart", "heading_changed", "idle",
                    "maptypeid_changed", "mousemove", "mouseout", "mouseover",
                    "projection_changed", "resize", "rightclick", "tilesloaded",
                    "tilt_changed", "zoom_changed"
                ],
                "mouse_events_with_latlng": [
                    "click", "dblclick", "mousemove", "mouseout", "mouseover", "rightclick"
                ],
            }
            cases.append({
                "name": "map_all_19_events_lifecycle",
                "passed": actual_ev == expected_ev,
                "expected": expected_ev,
                "actual": actual_ev,
            })
        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-ref-map-lab/explore-ref-map.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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