处理事件和用户互动

您可以处理 LocalContextMapView 实例和内部地图上的事件。LocalContextMapView 仅支持两个事件,这两个事件会在用户选择地点(打开地点详情视图)和关闭地点详情视图时触发。您可以通过这两个事件更新任何界面元素。

  • placedetailsviewshowstart 在用户选择地点后,地点详情视图显示之前触发。
  • placedetailsviewhidestart 在用户关闭地点详情视图后,地点详情视图隐藏之前触发。

以下示例展示了如何在 LocalContextMapView 实例上设置两个支持的监听器(您可在 initMap() 函数中执行此操作):

// Set the LocalContextMapView event handlers.
localContextMapView.addListener('placedetailsviewshowstart', () => {
  console.log("The 'placedetailsviewshowstart' event just fired!");
});

localContextMapView.addListener('placedetailsviewhidestart', () => {
  console.log("The 'placedetailsviewhidestart' event just fired!");
});

您还可以处理地图上通过 LocalContextMapView 创建的界面事件。以下示例展示了每当地图检测到鼠标悬停事件时就会触发的事件处理脚本:

// Set a mouseover event handler on the inner map.
localContextMapView.map.addListener('mouseover', () => {
  console.log("The mouse just entered the map!");
});

此外,LocalContextMapView 还会在用户按 Esc 键时关闭地点详情视图或照片灯箱。如果您想要更改此行为,建议您在捕获阶段将 keydown 事件和 Esc 键的监听器添加到窗口对象中,以拦截默认行为:

// Change the escape key behavior.
window.addEventListener('keydown', event => {
  if (event.key !== 'Escape') return;
  event.stopPropagation();
  // Handle the event.
  // ...
}, /* useCapture= */ true);

或者,若要允许 LocalContextMapView 在您的代码之前处理键盘事件,请在冒泡阶段在窗口上注册 keydown 监听器:

// Won't be fired if LocalContextMapView handled the escape key to close
// the place details view or photo lightbox:
window.addEventListener('keydown', event => {
  if (event.key !== 'Escape') return;
  // Handle the event.
  // ...
}, /* useCapture= */ false);

了解详情

  • 查看事件的实际用例!Local Context Library 示例演示了 Local Context Library 的常见用途,包括实现详情。
  • 详细了解 Maps JavaScript API 中的事件