我对 InfoBoxes 有一个 hack。它依赖于从 LatLng 到我在另一个问题中找到的屏幕像素的转换,fromLatLngToContainerPixel
. 谷歌文档描述告诉像素位置是在“地图的外部容器”中测量的。但是,回答者警告说,它的兄弟函数fromLatLngToDivPixel
. 不可靠,因为它会因调整大小或缩放而冻结。
所以,我的代码使用fromLatLngToContainerPixel
. 如果您尝试使用我的代码,请在您的代码中玩耍,看看是否需要更改偏移量。在我的代码中,我有一个固定的信息框宽度为 86 像素。
单击中心,然后单击可见区域的边缘。地图不会移动。
这是 JSFiddle:http: //jsfiddle.net/eHT9U/
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html, body { margin: 0; padding: 0; height: 100% }
#map_canvas { width: 100%; height: 300px }
#container { padding: 10px; }
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="infobox_alt.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var map;
var mapOptions = {
center: new google.maps.LatLng(40.0, -88.0),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var count = 0;
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map);
google.maps.event.addListener(map, 'click', function (event) {
count += 1;
pt = overlay.getProjection().fromLatLngToContainerPixel(event.latLng);
document.getElementById("end").value = pt;
addMarker(event.latLng, "index #" + Math.pow(100, count), pt.x, pt.y);
});
}
function addMarker(pos, content, x, y) {
var marker = new google.maps.Marker({
map: map,
position: pos
});
marker.setTitle(content);
var labelText = content;
var myOptions = {
content: labelText
,boxStyle: {
border: "1px solid black"
,background: "white"
,textAlign: "center"
,fontSize: "8pt"
,width: "86px" // has to be set manually
,opacity: 1.0
,zIndex: -100
}
,disableAutoPan: true
,position: marker.getPosition()
,closeBoxURL: ""
,pane: "floatPane"
,enableEventPropagation: true
,zIndex:-1
};
offX = -43;
offY = 0;
//compare boundaries
if(x > $("#map_canvas").width() - 60) {
offX = -86;
}
if(x < 60) {
offX = 0;
}
if(y > $("#map_canvas").height() - 60) {
offY = -50;
}
myOptions.pixelOffset = new google.maps.Size(offX,offY);
var ibLabel = new InfoBox(myOptions);
ibLabel.setZIndex(-1);
ibLabel.open(map);
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function (event) {
infowindow.open(map, this);
ibLabel.setZIndex(-1);
this.setZIndex(1);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
end: <input id="end" size="30">
<div id="container">
<div id="map_canvas"></div>
</div>
</body>
</html>