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

离线 Chromium 实测标记动画/自定义图标、折线多边形、米制圆投影与信息窗口

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-google-maps-overlays.py
explore-google-maps-overlays.py373 行
"""Offline Playwright Chromium lab for Google API Ch 04: google-maps-overlays."""
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: 560px; height: 400px; position: relative; border: 1px solid #94a3b8; overflow: hidden; background: #e2e8f0; }
  svg.gm-vector-layer { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; }
  .gm-marker { position: absolute; width: 16px; height: 16px; margin-left: -8px; margin-top: -8px; border-radius: 50%; background: #dc2626; }
  .gm-marker.bounce { outline: 2px dashed #f59e0b; }
  .gm-infowindow { position: absolute; background: #fff; border: 1px solid #334155; padding: 6px 10px; border-radius: 4px; font-size: 13px; }
</style>
</head>
<body>
<div id="googleMap"></div>
<script>
(function () {
  const TILE_SIZE = 256;
  const SVG_NS = "http://www.w3.org/2000/svg";

  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)),
    };
  }

  const MapTypeId = { ROADMAP: "roadmap", SATELLITE: "satellite", HYBRID: "hybrid", TERRAIN: "terrain" };
  const Animation = { BOUNCE: 1, DROP: 2 };

  function Map(div, opts) {
    this._div = div;
    this._center = opts.center;
    this._zoom = opts.zoom;
    this._mapTypeId = opts.mapTypeId || MapTypeId.ROADMAP;
    this._svg = document.createElementNS(SVG_NS, "svg");
    this._svg.setAttribute("class", "gm-vector-layer");
    this._svg.setAttribute("viewBox", "0 0 " + div.clientWidth + " " + div.clientHeight);
    div.innerHTML = "";
    div.appendChild(this._svg);
  }
  Map.prototype.latLngToPixel = function (ll) {
    const scale = Math.pow(2, this._zoom);
    const c = project(this._center);
    const p = project(ll);
    return {
      x: Number((this._div.clientWidth / 2 + (p.x - c.x) * scale).toFixed(2)),
      y: Number((this._div.clientHeight / 2 + (p.y - c.y) * scale).toFixed(2)),
    };
  };
  Map.prototype.metersToPixels = function (meters, lat) {
    const metersPerPixel = (156543.03392 * Math.cos((lat * Math.PI) / 180)) / Math.pow(2, this._zoom);
    return Number((meters / metersPerPixel).toFixed(2));
  };

  function Marker(opts) {
    this._position = opts.position;
    this._animation = opts.animation || null;
    this._icon = opts.icon || "DEFAULT_ICON";
    this._draggable = Boolean(opts.draggable);
    this._el = null;
    if (opts.map) this.setMap(opts.map);
  }
  Marker.prototype.getPosition = function () { return this._position; };
  Marker.prototype.getAnimation = function () { return this._animation; };
  Marker.prototype.getIcon = function () { return this._icon; };
  Marker.prototype.getDraggable = function () { return this._draggable; };
  Marker.prototype.setMap = function (map) {
    if (this._el && this._el.parentNode) this._el.parentNode.removeChild(this._el);
    this._map = map;
    if (!map) return;
    const px = map.latLngToPixel(this._position);
    const el = document.createElement("div");
    el.className = "gm-marker" + (this._animation === Animation.BOUNCE ? " bounce" : "");
    el.style.left = px.x + "px";
    el.style.top = px.y + "px";
    el.dataset.icon = this._icon;
    el.dataset.draggable = String(this._draggable);
    map._div.appendChild(el);
    this._el = el;
  };

  function Polyline(opts) {
    this._opts = Object.assign({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 2, editable: false }, opts);
    this._el = null;
  }
  Polyline.prototype.getPath = function () { return this._opts.path; };
  Polyline.prototype.setMap = function (map) {
    if (this._el && this._el.parentNode) this._el.parentNode.removeChild(this._el);
    if (!map) return;
    const pts = this._opts.path.map(ll => { const p = map.latLngToPixel(ll); return p.x + "," + p.y; }).join(" ");
    const el = document.createElementNS(SVG_NS, "polyline");
    el.setAttribute("points", pts);
    el.setAttribute("fill", "none");
    el.setAttribute("stroke", this._opts.strokeColor);
    el.setAttribute("stroke-opacity", String(this._opts.strokeOpacity));
    el.setAttribute("stroke-width", String(this._opts.strokeWeight));
    el.dataset.editable = String(Boolean(this._opts.editable));
    map._svg.appendChild(el);
    this._el = el;
  };

  function Polygon(opts) {
    this._opts = Object.assign({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 2, fillColor: "#000000", fillOpacity: 0.35, editable: false }, opts);
    this._el = null;
  }
  Polygon.prototype.getPath = function () { return this._opts.path; };
  Polygon.prototype.setMap = function (map) {
    if (this._el && this._el.parentNode) this._el.parentNode.removeChild(this._el);
    if (!map) return;
    const pts = this._opts.path.map(ll => { const p = map.latLngToPixel(ll); return p.x + "," + p.y; }).join(" ");
    const el = document.createElementNS(SVG_NS, "polygon");
    el.setAttribute("points", pts);
    el.setAttribute("stroke", this._opts.strokeColor);
    el.setAttribute("stroke-opacity", String(this._opts.strokeOpacity));
    el.setAttribute("stroke-width", String(this._opts.strokeWeight));
    el.setAttribute("fill", this._opts.fillColor);
    el.setAttribute("fill-opacity", String(this._opts.fillOpacity));
    el.dataset.editable = String(Boolean(this._opts.editable));
    map._svg.appendChild(el);
    this._el = el;
  };

  function Circle(opts) {
    this._opts = Object.assign({ strokeColor: "#000000", strokeOpacity: 1.0, strokeWeight: 2, fillColor: "#000000", fillOpacity: 0.35, editable: false }, opts);
    this._el = null;
  }
  Circle.prototype.getRadius = function () { return this._opts.radius; };
  Circle.prototype.setMap = function (map) {
    if (this._el && this._el.parentNode) this._el.parentNode.removeChild(this._el);
    if (!map) return;
    const c = map.latLngToPixel(this._opts.center);
    const rPx = map.metersToPixels(this._opts.radius, this._opts.center.lat());
    const el = document.createElementNS(SVG_NS, "circle");
    el.setAttribute("cx", String(c.x));
    el.setAttribute("cy", String(c.y));
    el.setAttribute("r", String(rPx));
    el.setAttribute("stroke", this._opts.strokeColor);
    el.setAttribute("stroke-opacity", String(this._opts.strokeOpacity));
    el.setAttribute("stroke-width", String(this._opts.strokeWeight));
    el.setAttribute("fill", this._opts.fillColor);
    el.setAttribute("fill-opacity", String(this._opts.fillOpacity));
    el.dataset.editable = String(Boolean(this._opts.editable));
    map._svg.appendChild(el);
    this._el = el;
  };

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

  window.google = { maps: { LatLng, Map, MapTypeId, Animation, Marker, Polyline, Polygon, Circle, InfoWindow } };
})();
</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: Basic marker, BOUNCE animation (vs draggable), custom icon
            actual_marker = page.evaluate("""() => {
                const london = new google.maps.LatLng(51.508742, -0.120850);
                window.__map = new google.maps.Map(document.getElementById("googleMap"), {
                    center: london, zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP
                });
                const mBasic = new google.maps.Marker({ position: london });
                mBasic.setMap(window.__map);
                const mBounce = new google.maps.Marker({
                    position: london,
                    animation: google.maps.Animation.BOUNCE,
                    draggable: true
                });
                mBounce.setMap(window.__map);
                const mIcon = new google.maps.Marker({
                    position: london,
                    icon: "pinkball.png"
                });
                mIcon.setMap(window.__map);
                window.__basicMarker = mBasic;
                const nodes = document.querySelectorAll(".gm-marker");
                return {
                    dom_marker_count: nodes.length,
                    basic_icon: mBasic.getIcon(),
                    bounce_animation_code: mBounce.getAnimation(),
                    bounce_has_css_class: mBounce._el.classList.contains("bounce"),
                    bounce_draggable: mBounce.getDraggable(),
                    custom_icon: mIcon.getIcon(),
                    pixel_pos: [mBasic._el.style.left, mBasic._el.style.top]
                };
            }""")
            expected_marker = {
                "dom_marker_count": 3,
                "basic_icon": "DEFAULT_ICON",
                "bounce_animation_code": 1,
                "bounce_has_css_class": True,
                "bounce_draggable": True,
                "custom_icon": "pinkball.png",
                "pixel_pos": ["280px", "200px"],
            }
            cases.append({
                "name": "marker_basic_bounce_and_icon",
                "passed": actual_marker == expected_marker,
                "expected": expected_marker,
                "actual": actual_marker,
            })

            # Case 2: Polyline & Polygon vectors (Stavanger -> Amsterdam -> London)
            actual_vec = page.evaluate("""() => {
                const stavanger = new google.maps.LatLng(58.983991, 5.734863);
                const amsterdam = new google.maps.LatLng(52.395715, 4.888916);
                const london = new google.maps.LatLng(51.508742, -0.120850);
                const flightPath = new google.maps.Polyline({
                    path: [stavanger, amsterdam, london],
                    strokeColor: "#0000FF",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    editable: true
                });
                flightPath.setMap(window.__map);

                const flightArea = new google.maps.Polygon({
                    path: [stavanger, amsterdam, london, stavanger],
                    strokeColor: "#0000FF",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#0000FF",
                    fillOpacity: 0.4
                });
                flightArea.setMap(window.__map);

                const pl = document.querySelector("svg polyline");
                const pg = document.querySelector("svg polygon");
                return {
                    polyline_vertices: flightPath.getPath().length,
                    polyline_stroke: pl.getAttribute("stroke"),
                    polyline_editable: pl.dataset.editable === "true",
                    polygon_vertices: flightArea.getPath().length,
                    polygon_closed: flightArea.getPath()[0].lat() === flightArea.getPath()[3].lat(),
                    polygon_fill_opacity: Number(pg.getAttribute("fill-opacity")),
                    svg_points_rendered: pl.getAttribute("points").split(" ").length === 3 && pg.getAttribute("points").split(" ").length === 4
                };
            }""")
            expected_vec = {
                "polyline_vertices": 3,
                "polyline_stroke": "#0000FF",
                "polyline_editable": True,
                "polygon_vertices": 4,
                "polygon_closed": True,
                "polygon_fill_opacity": 0.4,
                "svg_points_rendered": True,
            }
            cases.append({
                "name": "polyline_and_polygon_vectors",
                "passed": actual_vec == expected_vec,
                "expected": expected_vec,
                "actual": actual_vec,
            })

            # Case 3: Circle centered at Amsterdam (radius 20000m)
            actual_circle = page.evaluate("""() => {
                const amsterdam = new google.maps.LatLng(52.395715, 4.888916);
                const myCity = new google.maps.Circle({
                    center: amsterdam,
                    radius: 20000,
                    strokeColor: "#0000FF",
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: "#0000FF",
                    fillOpacity: 0.4,
                    editable: false
                });
                myCity.setMap(window.__map);
                const el = document.querySelector("svg circle");
                return {
                    radius_meters: myCity.getRadius(),
                    svg_radius_px: Number(el.getAttribute("r")),
                    stroke_color: el.getAttribute("stroke"),
                    fill_opacity: Number(el.getAttribute("fill-opacity")),
                    editable: el.dataset.editable === "true"
                };
            }""")
            expected_circle = {
                "radius_meters": 20000,
                "svg_radius_px": 6.7,
                "stroke_color": "#0000FF",
                "fill_opacity": 0.4,
                "editable": False,
            }
            cases.append({
                "name": "circle_radius_projection",
                "passed": actual_circle == expected_circle,
                "expected": expected_circle,
                "actual": actual_circle,
            })

            # Case 4: InfoWindow open & close on marker
            actual_iw = page.evaluate("""() => {
                const iw = new google.maps.InfoWindow({ content: "Hello World!" });
                iw.open(window.__map, window.__basicMarker);
                const openNode = document.querySelector(".gm-infowindow");
                const text = openNode ? openNode.textContent : "";
                const visibleWhenOpen = Boolean(openNode);
                iw.close();
                const visibleAfterClose = Boolean(document.querySelector(".gm-infowindow"));
                return {
                    content: text,
                    visible_when_open: visibleWhenOpen,
                    visible_after_close: visibleAfterClose
                };
            }""")
            expected_iw = {
                "content": "Hello World!",
                "visible_when_open": True,
                "visible_after_close": False,
            }
            cases.append({
                "name": "infowindow_open_on_marker",
                "passed": actual_iw == expected_iw,
                "expected": expected_iw,
                "actual": actual_iw,
            })
        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-overlays-lab/explore-google-maps-overlays.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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