在Google Map V3中,如何在多边形内部和上方放置标签?
与V2不同,没有标签叠加。
当我使用maplabel库时,我可以将文本放在内部,但即使我指定了更高的Z-index,也不能放在上面。
谢谢
Phil
maplabel会在地图的mapPane上的画布上呈现其文本内容,而mapPane通常会渲染在floatPane中所有zIndex值之下。 若想将mapPane画布按照您的zIndex顺序进行排序,请尝试以下操作:
var mapLabel = new MapLabel({
position: new google.maps.LatLng(yourLat, yourLng),
text: 'test',
zIndex: 101} );
$(mapLabel.getPanes().mapPane).css('z-index', mapLabel.zIndex);
虽然有些晚了,但我遇到了同样的问题,这段代码可以很好地解决问题。
var triangleCoords = [
{ lat:30.655993, lng: 76.732375 },
{ lat: 30.651379, lng: 76.735808},
{ lat: 30.653456, lng: 76.729682}
]
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords ,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
attachPolygonInfoWindow(bermudaTriangle)
function attachPolygonInfoWindow(polygon) {
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(polygon, 'mouseover', function (e) {
infoWindow.setContent("Polygon Name");
var latLng = e.latLng;
infoWindow.setPosition(latLng);
infoWindow.open(map);
});
}
使用Google Maps Utility Library。
设置标签内容,找到您的多边形中心位置,就完成了 :)
var labelOptions = {
content: label,
boxStyle: {
textAlign: "center",
fontSize: "8pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-25, 0),
position: this.my_getBounds(gpoints).getCenter(),
closeBoxURL: "",
isHidden: false,
pane: "mapPane",
enableEventPropagation: true
};
var polygonLabel = new InfoBox(labelOptions);
polygonLabel.open(map);
首先,通过你自己的版本来扩展多边形类中缺失的函数,我们称其为poly_getBounds()
google.maps.Polygon.prototype.poly_getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds
}
添加以下内容来自定义标签:
function Labelx(opt_options) {
// Initialization
this.setValues(opt_options);
// Labelx specific
var span = this.span_ = document.createElement('span');
span.style.cssText = 'position: relative; left: 0%; top: -8px; ' +
'white-space: nowrap; border: 0px; font-family:arial; font-weight:bold;' +
'padding: 2px; background-color: #ddd; ' +
'opacity: .75; ' +
'filter: alpha(opacity=75); ' +
'-ms-filter: "alpha(opacity=75)"; ' +
'-khtml-opacity: .75; ' +
'-moz-opacity: .75;';
var div = this.div_ = document.createElement('div');
div.appendChild(span);
div.style.cssText = 'position: absolute; display: none';
};
现在使用它:
var lbl = new Labelx({ map: map, position: polygon.polygon.poly_getBounds().getCenter() },true);
lbl.set('text', 'Label 1');
position
字段。使用以下代码获取多边形的中心位置。
const bounds = new window.google.maps.LatLngBounds();
bounds.extend(new window.google.maps.LatLng(lat1,lng1));
bounds.extend(new window.google.maps.LatLng(lat2,lng2));
..
..
let polygonCenter = bounds.getCenter();