首页 > 解决方案 > 谷歌地图:在功能中获取点击位置

问题描述

我允许用户在谷歌地图中创建、编辑和删除多边形。用户可以决定为每个多边形输入文本,然后单击多边形时,该文本显示在信息窗口中。下面的代码显示了这是如何实现的。我的问题是我目前无法检测到点击事件的位置 - 我需要知道这一点,因为这是显示信息窗口的位置。我已经尝试了很多方法来完成这项工作。

在下面的代码中,tmfPolygonObjects[i][9] 包含要在信息窗口中显示的文本。

我不知何故需要在函数中捕获事件,但无法解决这个问题。任何建议都会非常受欢迎......

function tmfAddPolygonInfoWindowListener(myPolygon, i, myPolygonInfoWindow) { 
  tmfPolygon = myPolygon;
  tmfPolygonInfoWindow = myPolygonInfoWindow;
  tmfShowPolygonInfoWindowListener[i] = google.maps.event.addListener(tmfPolygon, 'click', (function(tmfPolygon, i) {
      return function() {
              tmfPolygonInfoWindow.setContent(tmfPolygonObjects[i][9]);

              // this is where I would set the position of the info window IF I could detect the event
              tmfPolygonInfoWindow.setPosition(event.latLng()); 
              tmfPolygonInfoWindow.open(map, tmfPolygon);
          }
      }
  })(tmfPolygon, i));
}

标签: javascriptgoogle-maps

解决方案


我设法自己解决了这个问题。只需将“事件”添加到返回函数()中。更新后的代码如下所示。

function tmfAddPolygonInfoWindowListener(myPolygon, i, myPolygonInfoWindow) { 

tmfPolygon = myPolygon;
  tmfPolygonInfoWindow = myPolygonInfoWindow;
  tmfShowPolygonInfoWindowListener[i] = google.maps.event.addListener(tmfPolygon, 'click', (function(tmfPolygon, i) {
      return function(event) {
              tmfPolygonInfoWindow.setContent(tmfPolygonObjects[i][9]);

          // this is where I would set the position of the info window IF I could detect the event
          tmfPolygonInfoWindow.setPosition(event.latLng); 
          tmfPolygonInfoWindow.open(map, tmfPolygon);
      }
  }
  })(tmfPolygon, i));
}

推荐阅读