Google API 教程
理解应用程序编程接口(API)的核心概念、Google Maps API v3 交互式地图的异步回调挂载契约与离线 Chromium 画布实测。
学完这一章,你能够
- 理解应用程序编程接口(API)的核心概念、Google Maps API v3 交互式地图的异步回调挂载契约与离线 Chromium 画布实测。
Google Maps API v3 教程概述
本系列教程围绕 Google Maps JavaScript API v3 讲解在网页中构建交互式地图的完整流程,涵盖 API Key 配置、基础地图初始化、叠加层绘制、事件监听、控件定制、地图类型切换以及核心类参考手册。在当前生产环境中,调用官方在线底图服务需要通过 Google Cloud 启用 Maps JavaScript API 并配置有效计费与 API Key;为保证本地可重复验证,本站所有实验均在离线 Chromium 浏览器中运行同等 Web Mercator 投影与 `google.maps` 契约测试壳。
什么是 API 与异步初始化契约
API 即应用程序编程接口(Application Programming Interface),本质上是操作系统、底层平台或在线服务向外部应用暴露的一组约定调用入口。应用程序不必直接操作底层绘图管线或网络协议细节,只需按接口契约传入参数(例如中心坐标、缩放级别),即可驱动目标系统执行渲染与状态更新。在本章离线 Chromium 实测中,解析 `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap` 的 `async`/`defer` 引导参数并触发 `initMap()` 后,程序在 `500×380` 像素的 `#googleMap` 容器中创建了以悉尼 `(-34.397, 150.644)` 为中心、`zoom=8`、`roadmap` 类型的地图实例(画布采样背景 RGB `[229, 236, 244]`);随后通过封装接口调用 `panTo({lat: 51.508742, lng: -0.12085})` 与 `setZoom(5)`,中心点自动投影至容器正中 `[250, 190]` 且东侧经度偏移为正,直观体现了 API 屏蔽底层投影与重绘细节的设计价值。
在离线 Chromium 中验证 callback=initMap 异步引导与地图接口封装
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
async/defer 可避免阻塞 HTML 解析,待脚本加载就绪后由回调机制调用全局 initMap() 函数,确保执行 new google.maps.Map(...) 时 google.maps 命名空间和目标 DOM 容器均已可用。