You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Google Maps API获取绘制图形的长宽并添加标签?

解决方案:获取Google Maps图形尺寸并添加标签

嘿,刚好之前做过类似的需求,给你梳理两个核心问题的解决办法:获取图形尺寸、添加动态标签,都是基于Google Maps API原生能力实现的,不需要额外工具~

一、获取图形的长和宽

Overlay事件参数里确实不会直接返回尺寸,但我们可以通过图形的getBounds()方法获取边界,再计算出需要的尺寸。分两种常见场景:

1. 规则图形(比如Rectangle矩形)

矩形的边界就是它本身的范围,直接计算即可:

// 假设你已经创建了Rectangle实例
const rectangle = new google.maps.Rectangle({
  map: yourMapInstance,
  bounds: new google.maps.LatLngBounds(
    new google.maps.LatLng(39.9042, 116.4074), // 西南角
    new google.maps.LatLng(39.9142, 116.4174)  // 东北角
  )
});

// 获取边界并计算尺寸
const bounds = rectangle.getBounds();
const ne = bounds.getNorthEast();
const sw = bounds.getSouthWest();

// 1. 经纬度差(适合显示相对范围)
const widthLng = ne.lng() - sw.lng(); // 经度方向宽度
const heightLat = ne.lat() - sw.lat(); // 纬度方向高度

// 2. 实际距离(米,更直观,需要加载geometry库)
const widthMeters = google.maps.geometry.spherical.computeDistanceBetween(
  new google.maps.LatLng(ne.lat(), sw.lng()), // 西北角
  ne // 东北角
);
const heightMeters = google.maps.geometry.spherical.computeDistanceBetween(
  sw, // 西南角
  new google.maps.LatLng(ne.lat(), sw.lng()) // 西北角
);

2. 不规则图形(比如Polygon多边形)

不规则图形没有固定的“长宽”,但可以取它的外接边界框来计算:

const polygon = new google.maps.Polygon({
  map: yourMapInstance,
  paths: [/* 你的多边形坐标数组 */]
});

// 获取多边形的外接边界
const bounds = polygon.getBounds();
// 后续计算和矩形完全一致,用上面的代码即可

⚠️ 注意:要使用computeDistanceBetween方法,加载API时必须带上geometry库:

<script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥&libraries=geometry"></script>

二、在图形上方添加标签

有两种常用方式,按需选择:

1. 用原生InfoWindow快速实现

InfoWindow是官方自带的弹窗组件,适合快速展示文本信息:

// 先获取图形中心坐标
const center = bounds.getCenter();

// 创建InfoWindow
const sizeLabel = new google.maps.InfoWindow({
  content: `宽度: ${widthMeters.toFixed(2)}m | 高度: ${heightMeters.toFixed(2)}m`,
  position: center,
  disableAutoPan: true, // 避免地图自动平移
  maxWidth: 200
});

// 显示标签
sizeLabel.open(yourMapInstance);

// 如果图形可以拖动/调整大小,监听变化更新标签
rectangle.addListener('bounds_changed', () => {
  const newBounds = rectangle.getBounds();
  const newCenter = newBounds.getCenter();
  // 重新计算尺寸
  const newWidth = google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng(newBounds.getNorthEast().lat(), newBounds.getSouthWest().lng()),
    newBounds.getNorthEast()
  );
  const newHeight = google.maps.geometry.spherical.computeDistanceBetween(
    newBounds.getSouthWest(),
    new google.maps.LatLng(newBounds.getNorthEast().lat(), newBounds.getSouthWest().lng())
  );
  // 更新标签内容和位置
  sizeLabel.setContent(`宽度: ${newWidth.toFixed(2)}m | 高度: ${newHeight.toFixed(2)}m`);
  sizeLabel.setPosition(newCenter);
});

2. 自定义OverlayView实现更灵活的标签

如果需要自定义样式(比如背景、字体、位置),可以用OverlayView创建完全自定义的标签:

class CustomSizeLabel extends google.maps.OverlayView {
  constructor(position, content, map) {
    super();
    this.position = position;
    this.content = content;
    this.map = map;
    this.div = null;
    this.setMap(map);
  }

  // 初始化标签DOM
  onAdd() {
    const labelDiv = document.createElement('div');
    labelDiv.style.cssText = `
      position: absolute;
      background: #fff;
      padding: 6px 10px;
      border-radius: 4px;
      box-shadow: 0 2px 6px rgba(0,0,0,0.15);
      font-size: 14px;
      color: #333;
      white-space: nowrap;
    `;
    labelDiv.textContent = this.content;
    this.div = labelDiv;

    // 添加到地图的覆盖层
    const panes = this.getPanes();
    panes.overlayLayer.appendChild(labelDiv);
  }

  // 绘制标签位置
  draw() {
    const projection = this.getProjection();
    const pixelPosition = projection.fromLatLngToDivPixel(this.position);

    if (pixelPosition) {
      // 把标签放在图形中心上方15px的位置
      this.div.style.left = `${pixelPosition.x - this.div.offsetWidth / 2}px`;
      this.div.style.top = `${pixelPosition.y - this.div.offsetHeight - 15}px`;
    }
  }

  // 更新标签内容
  updateContent(newContent) {
    this.content = newContent;
    if (this.div) this.div.textContent = newContent;
    this.draw(); // 重新绘制调整位置
  }

  // 更新标签位置
  updatePosition(newPosition) {
    this.position = newPosition;
    this.draw();
  }

  // 移除标签
  onRemove() {
    if (this.div) {
      this.div.parentNode.removeChild(this.div);
      this.div = null;
    }
  }
}

// 使用自定义标签
const customLabel = new CustomSizeLabel(
  center,
  `宽度: ${widthMeters.toFixed(2)}m | 高度: ${heightMeters.toFixed(2)}m`,
  yourMapInstance
);

// 监听图形变化更新标签
rectangle.addListener('bounds_changed', () => {
  const newBounds = rectangle.getBounds();
  const newCenter = newBounds.getCenter();
  const newWidth = google.maps.geometry.spherical.computeDistanceBetween(
    new google.maps.LatLng(newBounds.getNorthEast().lat(), newBounds.getSouthWest().lng()),
    newBounds.getNorthEast()
  );
  const newHeight = google.maps.geometry.spherical.computeDistanceBetween(
    newBounds.getSouthWest(),
    new google.maps.LatLng(newBounds.getNorthEast().lat(), newBounds.getSouthWest().lng())
  );
  customLabel.updateContent(`宽度: ${newWidth.toFixed(2)}m | 高度: ${newHeight.toFixed(2)}m`);
  customLabel.updatePosition(newCenter);
});

这样不管是规则还是不规则图形,都能获取到尺寸并添加动态更新的标签啦~

内容的提问来源于stack exchange,提问作者The.Wolfgang.Grimmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:03:30