Google 地图事件
掌握 google.maps.event.addListener 事件监听模型,实测点击标记缩放居中、center_changed 延时复位、点击弹窗及点击地图动态布点。
学完这一章,你能够
- 掌握 google.maps.event.addListener 事件监听模型,实测点击标记缩放居中、center_changed 延时复位、点击弹窗及点击地图动态布点。
事件注册机制与点击标记缩放地图
Google Maps JavaScript API 采用发布-订阅式事件模型,通过 `google.maps.event.addListener(instance, eventName, handler)` 为地图或叠加层注册回调函数(并返回可用于 `removeListener()` 注销的句柄)。继续沿用英国伦敦 `(51.508742, -0.120850)` 地图,当监听标记的 `click` 事件并在回调中执行 `map.setZoom(9)` 与 `map.setCenter(marker.getPosition())` 时,用户点击标记即可放大并聚焦该位置。本站离线 Chromium 通过真实 DOM 点击 `.gm-marker` 实测,点击后缩放级别准确从 `5` 升至 `9`,中心坐标锁定为 `(51.508742, -0.12085)`。
监听 center_changed 实现延时自动回中
除用户鼠标事件外,地图属性变更也会触发状态事件。监听地图的 `center_changed` 事件并在回调中通过 `window.setTimeout(() => map.panTo(marker.getPosition()), 3000)` 预约延时平移,可在地图中心偏离后 3 秒自动平滑回到原始标记处。工程实践中需注意防重入或清理旧定时器,避免频繁拖动堆积多个延时任务。本站 Chromium 实测将中心改至巴黎 `(48.8566, 2.3522)` 后捕获 `3000ms` 定时调度并验证地图自动归位至伦敦 `(51.508742, -0.12085)`。
点击标记打开信息窗口与点击地图动态放点
将 `InfoWindow` 与标记 `click` 事件结合,可在用户点击标记时按需弹出说明文本(如 `"Hello World!"`),避免初始加载即遮挡视野。本站实测点击标记后弹窗文本显示 `"Hello World!"`,调用 `removeListener()` 注销监听后再次点击,累计触发次数仍维持 `1` 次,验证了句柄解绑行为。
为地图容器本身注册 `click` 监听时,回调参数 `event` 会携带点击处经纬度 `event.latLng`。将其传入 `placeMarker(location)` 即可在该坐标动态创建新 `Marker`,同时打开展示 `Latitude: <lat><br>Longitude: <lng>` 的信息窗口。本站离线 Chromium 在 `#googleMap` 上于 `(120, 100)` 与 `(380, 260)` 执行两次真实点击,逆墨卡托反算结果分别位于中心西北侧与东南侧,页面动态新增 2 个标记(总计 3 个 DOM 标记)并渲染含经纬度标签的弹窗。完整事件清单见后续参考手册。
离线 Chromium 真实点击实测标记缩放、延时回中、信息弹窗与地图动态布点
"""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()
- 点击标记后 zoom 由 5 升至 9;中心改至巴黎触发 3000ms 回中调度归位伦敦;InfoWindow 打开后解绑监听计数保持 1;两次画布点击逆投影新增 2 个带经纬度弹窗的标记。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:4a34edc9eada03d9eb34ac9cd7fac0b4ad797f8c64926d761836403c815c64c2
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:0ef30d46845d65decdefaa932aecd73dcd9109691588f75beef6310ffba8f53e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 map 的 click 事件回调中如何取得点击位置的经纬度,以及如何防止不再需要的事件监听继续触发?
展开参考解答
通过回调参数 event.latLng 的 lat() 与 lng() 方法取得点击处纬度和经度;保存 addListener() 返回的 MapsEventListener 句柄,并在适当时机调用 google.maps.event.removeListener(handle) 解绑。