您需要首先获取多边形中心的坐标并将其用作标签坐标的值。为了得到多边形的中心,我按照这个SO 帖子的答案,然后使用坐标作为 labelOverlay中ll的值。
解释一下:首先,我注意到您在多边形之前创建了 labelOverlay。所以要得到多边形中心的坐标,需要把多边形移到labelOverlay之前。
然后,您将添加来自 SO 帖子的代码片段,以通过 extend() 方法将多边形的每个点传递给 LatLngBounds 对象。
获取边界的中心并将其用作 labelOverlay 中 ll 的值。
以下是代码的外观片段。您还可以在此处查看工作小提琴。
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757},
{lat: 25.774, lng: -80.190}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < triangleCoords.length; i++) {
bounds.extend(triangleCoords[i]);
}
var polygonCenter = bounds.getCenter();
var overlay1 = new LabelOverlay({
ll : polygonCenter,
//minBox : box,
minBoxH : 0.346,
minBoxW : 1.121,
maxBoxH : 0.09,
maxBoxW : 0.3,
//className : 'small',
debugBoxes : true,
debugVisibility : true,
maxZoom : 10,
minZoom : 6,
label : "Hello world",
map : map
});