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

离线 Chromium 真实点击实测标记缩放、延时回中、信息弹窗与地图动态布点

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-google-maps-events.py
explore-google-maps-events.py321 行
"""Offline Playwright Chromium lab for Google API Ch 05: google-maps-events."""
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: 500px; height: 380px; position: relative; border: 1px solid #94a3b8; background: #e2e8f0; overflow: hidden; }
  .gm-marker { position: absolute; width: 20px; height: 20px; margin-left: -10px; margin-top: -10px; border-radius: 50%; background: #ef4444; cursor: pointer; z-index: 2; }
  .gm-infowindow { position: absolute; background: #fff; border: 1px solid #334155; padding: 4px 8px; font-size: 12px; z-index: 3; }
</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 project(ll) {
    let siny = Math.sin((ll.lat() * Math.PI) / 180);
    siny = Math.min(Math.max(siny, -0.9999), 0.9999);
    return {
      x: TILE_SIZE * (0.5 + ll.lng() / 360),
      y: TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI)),
    };
  }
  function unproject(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(Number(((latRad * 180) / Math.PI).toFixed(4)), Number(lng.toFixed(4)));
  }

  const event = {
    addListener(instance, eventName, handler) {
      instance._listeners = instance._listeners || {};
      instance._listeners[eventName] = instance._listeners[eventName] || [];
      const handle = { instance, eventName, handler };
      instance._listeners[eventName].push(handle);
      return handle;
    },
    removeListener(handle) {
      const arr = handle.instance._listeners && handle.instance._listeners[handle.eventName];
      if (!arr) return;
      const idx = arr.indexOf(handle);
      if (idx >= 0) arr.splice(idx, 1);
    },
    trigger(instance, eventName, payload) {
      const arr = (instance._listeners && instance._listeners[eventName]) || [];
      for (const h of arr.slice()) h.handler(payload);
    },
  };

  function Map(div, opts) {
    this._div = div;
    this._center = opts.center;
    this._zoom = opts.zoom;
    this._listeners = {};
    this._markers = [];
    div.addEventListener("click", (e) => {
      if (e.target !== div) return;
      const rect = div.getBoundingClientRect();
      const ll = this.pixelToLatLng(e.clientX - rect.left, e.clientY - rect.top);
      event.trigger(this, "click", { latLng: ll });
    });
  }
  Map.prototype.getCenter = function () { return this._center; };
  Map.prototype.getZoom = function () { return this._zoom; };
  Map.prototype.setZoom = function (z) {
    this._zoom = Number(z);
    event.trigger(this, "zoom_changed");
  };
  Map.prototype.setCenter = function (ll) {
    this._center = ll;
    this._repositionMarkers();
    event.trigger(this, "center_changed");
  };
  Map.prototype.panTo = function (ll) { this.setCenter(ll); };
  Map.prototype.latLngToPixel = function (ll) {
    const scale = Math.pow(2, this._zoom);
    const c = project(this._center), p = project(ll);
    return {
      x: this._div.clientWidth / 2 + (p.x - c.x) * scale,
      y: this._div.clientHeight / 2 + (p.y - c.y) * scale,
    };
  };
  Map.prototype.pixelToLatLng = function (px, py) {
    const scale = Math.pow(2, this._zoom);
    const c = project(this._center);
    return unproject({
      x: c.x + (px - this._div.clientWidth / 2) / scale,
      y: c.y + (py - this._div.clientHeight / 2) / scale,
    });
  };
  Map.prototype._repositionMarkers = function () {
    for (const m of this._markers) m._place();
  };

  function Marker(opts) {
    this._position = opts.position;
    this._title = opts.title || "";
    this._listeners = {};
    this._el = null;
    if (opts.map) this.setMap(opts.map);
  }
  Marker.prototype.getPosition = function () { return this._position; };
  Marker.prototype.setMap = function (map) {
    this._map = map;
    if (!map) return;
    const el = document.createElement("div");
    el.className = "gm-marker";
    el.title = this._title;
    el.addEventListener("click", (e) => {
      e.stopPropagation();
      event.trigger(this, "click", { latLng: this._position });
    });
    map._div.appendChild(el);
    map._markers.push(this);
    this._el = el;
    this._place();
  };
  Marker.prototype._place = function () {
    if (!this._el || !this._map) return;
    const p = this._map.latLngToPixel(this._position);
    this._el.style.left = p.x + "px";
    this._el.style.top = p.y + "px";
  };

  function InfoWindow(opts) {
    this._content = opts.content || "";
    this._el = null;
  }
  InfoWindow.prototype.open = function (map, anchor) {
    if (this._el && this._el.parentNode) this._el.parentNode.removeChild(this._el);
    const p = map.latLngToPixel(anchor.getPosition());
    const el = document.createElement("div");
    el.className = "gm-infowindow";
    el.innerHTML = this._content;
    el.style.left = (p.x + 12) + "px";
    el.style.top = (p.y - 24) + "px";
    map._div.appendChild(el);
    this._el = el;
  };

  window.google = { maps: { LatLng, Map, Marker, InfoWindow, 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: Click marker -> zoom to 9 & center on marker
            page.evaluate("""() => {
                const myCenter = new google.maps.LatLng(51.508742, -0.120850);
                window.__map = new google.maps.Map(document.getElementById("googleMap"), {
                    center: myCenter, zoom: 5
                });
                window.__marker = new google.maps.Marker({
                    position: myCenter, title: "Click to zoom"
                });
                window.__marker.setMap(window.__map);
                window.__zoomHandle = google.maps.event.addListener(window.__marker, "click", function () {
                    window.__map.setZoom(9);
                    window.__map.setCenter(window.__marker.getPosition());
                });
            }""")
            page.locator(".gm-marker").first.click()
            actual_zoom = page.evaluate("""() => ({
                zoom_after_click: window.__map.getZoom(),
                center_lat: Number(window.__map.getCenter().lat().toFixed(6)),
                center_lng: Number(window.__map.getCenter().lng().toFixed(6))
            })""")
            expected_zoom = {
                "zoom_after_click": 9,
                "center_lat": 51.508742,
                "center_lng": -0.12085,
            }
            cases.append({
                "name": "marker_click_zoom_and_center",
                "passed": actual_zoom == expected_zoom,
                "expected": expected_zoom,
                "actual": actual_zoom,
            })

            # Case 2: center_changed -> scheduled 3000ms panTo back to marker
            actual_recenter = page.evaluate("""() => {
                const scheduled = [];
                const origSetTimeout = window.setTimeout;
                let guard = false;
                window.setTimeout = function (fn, ms) {
                    scheduled.push(ms);
                    if (!guard) {
                        guard = true;
                        fn();
                    }
                    return 1;
                };
                const handle = google.maps.event.addListener(window.__map, "center_changed", function () {
                    window.setTimeout(function () {
                        window.__map.panTo(window.__marker.getPosition());
                    }, 3000);
                });
                const paris = new google.maps.LatLng(48.8566, 2.3522);
                window.__map.setCenter(paris);
                google.maps.event.removeListener(handle);
                window.setTimeout = origSetTimeout;
                return {
                    scheduled_delay_ms: scheduled[0],
                    recentered_lat: Number(window.__map.getCenter().lat().toFixed(6)),
                    recentered_lng: Number(window.__map.getCenter().lng().toFixed(6))
                };
            }""")
            expected_recenter = {
                "scheduled_delay_ms": 3000,
                "recentered_lat": 51.508742,
                "recentered_lng": -0.12085,
            }
            cases.append({
                "name": "center_changed_auto_recenter",
                "passed": actual_recenter == expected_recenter,
                "expected": expected_recenter,
                "actual": actual_recenter,
            })

            # Case 3: Click marker -> open InfoWindow ("Hello World!") & removeListener
            page.evaluate("""() => {
                google.maps.event.removeListener(window.__zoomHandle);
                window.__iwCount = 0;
                const infowindow = new google.maps.InfoWindow({ content: "Hello World!" });
                window.__iwHandle = google.maps.event.addListener(window.__marker, "click", function () {
                    window.__iwCount += 1;
                    infowindow.open(window.__map, window.__marker);
                });
            }""")
            page.locator(".gm-marker").first.click()
            page.evaluate("() => google.maps.event.removeListener(window.__iwHandle)")
            page.locator(".gm-marker").first.click()
            actual_iw = page.evaluate("""() => ({
                infowindow_text: document.querySelector(".gm-infowindow").textContent,
                trigger_count_after_remove: window.__iwCount
            })""")
            expected_iw = {
                "infowindow_text": "Hello World!",
                "trigger_count_after_remove": 1,
            }
            cases.append({
                "name": "marker_click_infowindow",
                "passed": actual_iw == expected_iw,
                "expected": expected_iw,
                "actual": actual_iw,
            })

            # Case 4: Click map -> placeMarker(event.latLng) + coordinate InfoWindow
            page.evaluate("""() => {
                window.__placed = [];
                function placeMarker(location) {
                    const marker = new google.maps.Marker({ position: location, map: window.__map });
                    const iw = new google.maps.InfoWindow({
                        content: "Latitude: " + location.lat() + "<br>Longitude: " + location.lng()
                    });
                    iw.open(window.__map, marker);
                    window.__placed.push({ lat: location.lat(), lng: location.lng(), html: iw._content });
                }
                google.maps.event.addListener(window.__map, "click", function (ev) {
                    placeMarker(ev.latLng);
                });
            }""")
            page.locator("#googleMap").click(position={"x": 120, "y": 100})
            page.locator("#googleMap").click(position={"x": 380, "y": 260})
            actual_place = page.evaluate("""() => ({
                placed_count: window.__placed.length,
                first_north_west_of_center: window.__placed[0].lat > 51.508742 && window.__placed[0].lng < -0.12085,
                second_south_east_of_center: window.__placed[1].lat < 51.508742 && window.__placed[1].lng > -0.12085,
                first_has_coord_labels: window.__placed[0].html.includes("Latitude:") && window.__placed[0].html.includes("<br>Longitude:"),
                total_dom_markers: document.querySelectorAll(".gm-marker").length
            })""")
            expected_place = {
                "placed_count": 2,
                "first_north_west_of_center": True,
                "second_south_east_of_center": True,
                "first_has_coord_labels": True,
                "total_dom_markers": 3,
            }
            cases.append({
                "name": "map_click_place_marker_and_coords",
                "passed": actual_place == expected_place,
                "expected": expected_place,
                "actual": actual_place,
            })
        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-events-lab/explore-google-maps-events.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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