使用重叠标记Spiderfier时获得地图标记的新位置

时间:2019-04-17 16:05:01

标签: javascript google-maps oms

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

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坐标的变化?

1 个答案:

答案 0 :(得分:1)

问题出在函数getPixelPosition上。我们可以轻松地更改此行

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

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

经过大量计算后,所有oms都使用gmaps自己的setPosition方法更新了google maps标记的位置,因此效果很好。

Updated, working example

相关问题