1

我有一个带有标记的谷歌地图,它使用OverlappingMarkerSpiderfier来传播非常紧密重叠的标记。我需要检索鼠标事件上标记的屏幕位置(在真实版本中,我制作的工具提示过于复杂,无法嵌入谷歌提供的默认值)。

function project(latLng) {
  var TILE_SIZE = 256;
  var siny = Math.sin(latLng.lat * Math.PI / 180);

  siny = Math.min(Math.max(siny, -0.9999), 0.9999);

  return new google.maps.Point(
      TILE_SIZE * (0.5 + latLng.lng / 360),
      TILE_SIZE * (0.5 - Math.log((1 + siny) / (1 - siny)) / (4 * Math.PI)));
}

function getPixelPosition(marker, map) {
  var zoom = map.getZoom();
  var scale = 1 << zoom;
  var loc = marker.data.location;
  var worldCoordinate = project(loc);
  var pixelCoordinate = new google.maps.Point(
      Math.floor(worldCoordinate.x * scale),
      Math.floor(worldCoordinate.y * scale));

  return pixelCoordinate;
}

function getMapTopLeftPosition(map) {
  var zoom = map.getZoom();
  var scale = 1 << zoom;
  var topLeft = new google.maps.LatLng(
        map.getBounds().getNorthEast().lat(),
        map.getBounds().getSouthWest().lng());
  var projection = map.getProjection();
  var topLeftWorldCoordinate = projection.fromLatLngToPoint(topLeft);
  var topLeftPixelCoordinate = new google.maps.Point(
          topLeftWorldCoordinate.x * scale,
          topLeftWorldCoordinate.y * scale);

  return topLeftPixelCoordinate;
}

function getMarkerRelativePosition(marker, map) {
  const screenPosition = getPixelPosition(marker, map);

  const topLeftMapPosition = getMapTopLeftPosition(map);

  const markerHeight = 60;
  const markerWidth = 48;
  return {
    x: screenPosition.x - topLeftMapPosition.x - (markerWidth / 2),
    y: screenPosition.y - topLeftMapPosition.y - markerHeight,
  };
}

function showInfo(position, text) {
  // triggered on marker mouseover
  const mapContainer = document.getElementById('map-container');
  const infoDiv = document.createElement('div');
  infoDiv.innerHTML = text;
  infoDiv.setAttribute('id', 'info')
  infoDiv.style.left = position.x + 'px';
  infoDiv.style.top = position.y + 'px';
  mapContainer.appendChild(infoDiv);
}

function hideInfo() {
  // triggered on marker mouseout
  const info = document.getElementById('info')
  info.remove();
}

这适用于 OMS 尚未从集群中展开的标记。但是,当我单击一组标记来展开它们时,上面的代码仍然返回标记的原始位置。请参阅此处的工作示例:https ://jsfiddle.net/ebbishop/s2mzgp0b/

我怀疑有一种方法可以使用 oms 库获取标记的新位置,但我无法在文档中找到它。

如何检索标记的新位置或 x 和 y 坐标的变化?

4

1 回答 1

1

问题是功能getPixelPosition。我们可以很容易地改变这条线

var loc = marker.data.location,它使用自定义的静态数据属性集用于其他目的,并将其替换为

var loc = { lat: marker.getPosition().lat(), lng: marker.getPosition().lng() },它获取标记的当前位置。

经过大量计算后,所有oms操作都是使用 gmaps 自己的setPosition方法更新谷歌地图标记的位置,所以这工作得很好。

更新的工作示例

于 2019-04-17T18:48:12.000 回答