如何在Google Maps JS API指定经纬度位置添加文本?
在Google Maps JS API指定经纬度添加文本的简单方法
目前Google Maps JS API没有直接的「添加文本」专属接口,但有两种官方支持、无需依赖废弃库的简单实现方案:
方法一:用Marker的Label属性(适合短文本)
这是最省心的方式,利用Marker的label参数直接显示文本,还可以隐藏默认的Marker图标,只保留文本:
// 初始化地图 const map = new google.maps.Map(document.getElementById("map"), { zoom: 12, center: { lat: 37.7749, lng: -122.4194 }, // 示例坐标:旧金山 }); // 创建仅显示文本的Marker const textMarker = new google.maps.Marker({ position: { lat: 37.7749, lng: -122.4194 }, map: map, label: { text: "我的自定义文本", color: "#ff0000", fontSize: "16px", fontWeight: "bold", }, // 隐藏默认Marker图标 icon: { url: "data:image/svg+xml;charset=utf-8,%3Csvg%20width%3D%220%22%20height%3D%220%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%2F%3E", scaledSize: new google.maps.Size(0, 0), }, });
这种方式代码量少、无需额外封装,适合简短标注类文本。
方法二:自定义OverlayView(适合复杂样式/长文本)
如果需要多行文本、自定义背景、支持HTML格式等复杂需求,官方提供的OverlayView自定义覆盖物是标准解决方案:
class TextOverlay extends google.maps.OverlayView { constructor(position, text, map) { super(); this.position = position; this.text = text; this.map = map; this.div = null; this.setMap(map); } onAdd() { // 创建文本容器,自定义样式 this.div = document.createElement("div"); this.div.style.position = "absolute"; this.div.style.color = "#2c3e50"; this.div.style.fontSize = "18px"; this.div.style.padding = "4px 8px"; this.div.style.background = "rgba(255,255,255,0.8)"; this.div.style.borderRadius = "4px"; this.div.style.whiteSpace = "nowrap"; // 如果需要支持HTML,用innerHTML代替textContent this.div.textContent = this.text; // 把容器添加到地图的覆盖物层级 const panes = this.getPanes(); panes.overlayLayer.appendChild(this.div); } draw() { // 将经纬度转换为地图上的像素坐标,自动对齐位置 const projection = this.getProjection(); const point = projection.fromLatLngToDivPixel(this.position); if (point) { this.div.style.left = `${point.x - this.div.offsetWidth / 2}px`; this.div.style.top = `${point.y - this.div.offsetHeight / 2}px`; } } onRemove() { if (this.div) { this.div.parentNode.removeChild(this.div); this.div = null; } } } // 使用示例 const map = new google.maps.Map(document.getElementById("map"), { zoom: 12, center: { lat: 37.7749, lng: -122.4194 }, }); // 在指定经纬度添加自定义文本 new TextOverlay( new google.maps.LatLng(37.7749, -122.4194), "这是支持自定义样式的文本", map );
这个方案完全可控,地图缩放、拖动时会自动更新文本位置,适合复杂的文本展示需求。
注意事项
- Marker的Label适合短文本,过长会导致显示不全;
- 自定义OverlayView支持HTML内容,只需把
textContent换成innerHTML即可; - 确保加载Google Maps API时带上你的API密钥:
<script src="https://maps.googleapis.com/maps/api/js?key=你的API密钥"></script>
内容的提问来源于stack exchange,提问作者Fredy31
相关产品推荐
相关产品推荐

