谷歌地图API-地图顶部的文本

Google Maps API - Text on top of map

本文关键字:文本 顶部 地图 API- 谷歌地图      更新时间:2023-09-26

问题:即使在放大/缩小或平移时,是否可以使用Google Maps API在固定位置创建悬停在窗口上方的文本?

到目前为止我尝试了什么:我已经知道信息窗口可以使用以下代码:

var contentString = "<div>Hello!</div>";
var infowindow = new google.maps.InfoWindow({
          content: contentString
});
marker.addListener('click', function() {
          infowindow.open(map, marker);
});

但之前的信息窗口需要一个标记,据我所知,标记在地图上只能有固定的位置(我不知道如何在屏幕中央放置标记,即使用户在移动地图时也要将其保持在那里)

有人知道把文字放在地图中间的方法吗?它可以是信息窗口或其他方法。

如果您想使用InfoWindow,您只需为标记设置visible: false,然后在地图中心位置发生变化时更改标记的位置:

/* Invisible marker for the InfoWindow */
textmarker = new google.maps.Marker({
    position: map.getCenter(),
    map: map,
    visible: false
});
/* Center change handler to always center the marker */
map.addListener('center_changed', function() {
    textmarker.setPosition(map.getCenter());
});
/* adding the info window */
var infowindow = new google.maps.InfoWindow({
    content: "Your Text can be placed here"
    });
infowindow.open(map, textmarker);

工作小提琴:https://jsfiddle.net/7rtsv2y4/

假设文本位于地图上方的静态位置,则可以使用CSS:来完成此操作

<div class="map-container">
 <-- google map div here -->
 <div class="textbox">Static Text</div>
</div>

CSS:

.map-container {
  position: relative;
}
.textbox {
  position: absolute;
  left: 50%:
  top: 50%;
  transform: translateX(-50%);
  transform: translateY(-50%);
  z-index: 1000;
}