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

在离线 Chromium 中验证 callback=initMap 异步引导与地图接口封装

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial.py
explore-tutorial.py231 行
"""Offline Playwright Chromium lab for Google API Ch 01: tutorial."""
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 API v3 离线入门实验</title>
<style>
  body { margin: 0; font-family: sans-serif; }
  #googleMap { width: 500px; height: 380px; position: relative; border: 1px solid #94a3b8; overflow: hidden; }
  canvas.gm-tile-canvas { display: block; width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="googleMap"></div>
<script id="maps-loader-spec" type="text/plain"
  data-src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
  data-async="true" data-defer="true"></script>
<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; };
  LatLng.prototype.toJSON = function () { return { lat: this._lat, lng: this._lng }; };

  function normalizeLatLng(val) {
    if (val instanceof LatLng) return val;
    return new LatLng(val.lat, val.lng);
  }

  function mercatorProject(latLng) {
    let siny = Math.sin((latLng.lat() * Math.PI) / 180);
    siny = Math.min(Math.max(siny, -0.9999), 0.9999);
    const x = TILE_SIZE * (0.5 + latLng.lng() / 360);
    const y = TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI));
    return { x, y };
  }

  const MapTypeId = {
    ROADMAP: "roadmap",
    SATELLITE: "satellite",
    HYBRID: "hybrid",
    TERRAIN: "terrain",
  };

  function Map(container, opts) {
    this._div = container;
    this._center = normalizeLatLng(opts.center || { lat: 0, lng: 0 });
    this._zoom = typeof opts.zoom === "number" ? opts.zoom : 2;
    this._mapTypeId = opts.mapTypeId || MapTypeId.ROADMAP;
    this._canvas = document.createElement("canvas");
    this._canvas.className = "gm-tile-canvas";
    this._canvas.width = container.clientWidth || 500;
    this._canvas.height = container.clientHeight || 380;
    container.innerHTML = "";
    container.appendChild(this._canvas);
    this._render();
  }
  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.setZoom = function (z) { this._zoom = Number(z); this._render(); };
  Map.prototype.panTo = function (ll) { this._center = normalizeLatLng(ll); this._render(); };
  Map.prototype.latLngToPixel = function (ll) {
    const scale = Math.pow(2, this._zoom);
    const c = mercatorProject(this._center);
    const p = mercatorProject(normalizeLatLng(ll));
    return {
      x: Math.round(this._canvas.width / 2 + (p.x - c.x) * scale),
      y: Math.round(this._canvas.height / 2 + (p.y - c.y) * scale),
    };
  };
  Map.prototype._render = function () {
    const ctx = this._canvas.getContext("2d");
    const w = this._canvas.width, h = this._canvas.height;
    ctx.fillStyle = "#e5ecf4";
    ctx.fillRect(0, 0, w, h);
    ctx.strokeStyle = "#cbd5e1";
    ctx.lineWidth = 1;
    for (let x = 0; x <= w; x += 50) {
      ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();
    }
    for (let y = 0; y <= h; y += 50) {
      ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke();
    }
    ctx.fillStyle = "#0f172a";
    ctx.font = "12px sans-serif";
    ctx.fillText("Offline Map z=" + this._zoom + " (" + this._center.lat().toFixed(3) + "," + this._center.lng().toFixed(3) + ")", 12, 20);
  };

  window.google = { maps: { LatLng, Map, MapTypeId } };
})();

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById("googleMap"), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
  });
  window.__initMapCalled = true;
}
</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: async callback bootstrap parsing & initMap invocation
            actual_boot = page.evaluate("""() => {
                const el = document.getElementById('maps-loader-spec');
                const url = new URL(el.dataset.src);
                const cb = url.searchParams.get('callback');
                if (typeof window[cb] === 'function') window[cb]();
                return {
                    protocol: url.protocol,
                    pathname: url.pathname,
                    callback: cb,
                    async_flag: el.dataset.async === 'true',
                    defer_flag: el.dataset.defer === 'true',
                    initialized: Boolean(window.__initMapCalled && window.map)
                };
            }""")
            expected_boot = {
                "protocol": "https:",
                "pathname": "/maps/api/js",
                "callback": "initMap",
                "async_flag": True,
                "defer_flag": True,
                "initialized": True,
            }
            cases.append({
                "name": "async_callback_bootstrap",
                "passed": actual_boot == expected_boot,
                "expected": expected_boot,
                "actual": actual_boot,
            })

            # Case 2: Sydney map initialization & canvas verification
            actual_init = page.evaluate("""() => {
                const div = map.getDiv();
                const canvas = div.querySelector('canvas');
                const ctx = canvas.getContext('2d');
                const px = Array.from(ctx.getImageData(10, 10, 1, 1).data);
                const c = map.getCenter();
                return {
                    div_id: div.id,
                    width: canvas.width,
                    height: canvas.height,
                    lat: Number(c.lat().toFixed(3)),
                    lng: Number(c.lng().toFixed(3)),
                    zoom: map.getZoom(),
                    map_type: map.getMapTypeId(),
                    bg_rgb: px.slice(0, 3)
                };
            }""")
            expected_init = {
                "div_id": "googleMap",
                "width": 500,
                "height": 380,
                "lat": -34.397,
                "lng": 150.644,
                "zoom": 8,
                "map_type": "roadmap",
                "bg_rgb": [229, 236, 244],
            }
            cases.append({
                "name": "init_map_sydney_canvas",
                "passed": actual_init == expected_init,
                "expected": expected_init,
                "actual": actual_init,
            })

            # Case 3: API interface encapsulation (panTo + setZoom + Mercator projection)
            actual_api = page.evaluate("""() => {
                map.panTo({ lat: 51.508742, lng: -0.12085 });
                map.setZoom(5);
                const centerPx = map.latLngToPixel(map.getCenter());
                const eastPx = map.latLngToPixel({ lat: 51.508742, lng: 1.87915 });
                return {
                    lat: Number(map.getCenter().lat().toFixed(6)),
                    lng: Number(map.getCenter().lng().toFixed(5)),
                    zoom: map.getZoom(),
                    center_pixel: [centerPx.x, centerPx.y],
                    east_shift_positive: eastPx.x > centerPx.x && eastPx.y === centerPx.y
                };
            }""")
            expected_api = {
                "lat": 51.508742,
                "lng": -0.12085,
                "zoom": 5,
                "center_pixel": [250, 190],
                "east_shift_positive": True,
            }
            cases.append({
                "name": "api_interface_contract",
                "passed": actual_api == expected_api,
                "expected": expected_api,
                "actual": actual_api,
            })
        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-tutorial-lab/explore-tutorial.py

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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