扩展Google地图边界,以便div叠加层不会覆盖任何标记

时间:2011-01-26 07:36:32

标签: javascript google-maps google-maps-api-3

在我正在处理的谷歌地图混搭中,地图是100%宽,几乎100%高,我有一个水平透明div,使用z-index和CSS覆盖地图的左侧。

当我动态添加标记时,我从一个空的Bounds对象开始并逐个扩展它以包含新的LatLng。但有时标记会显示在包含其他元素的透明div下。

假设我的透明div是250像素宽。

我想做的是,一旦我的边界显示所有标记都已建立,我想再延长它们以扩展Google Map的视口,以便在我符合界限时,这些标记现在距左边界至少250像素,这样它们就不会被透明div覆盖。

我尝试使用MapProjection.fromPointToLatLngMapCanvasProjection.fromDivPointToLatLng,但无法获得可预测的结果。

任何建议或例子都将不胜感激。

1 个答案:

答案 0 :(得分:1)

希望这个快速而肮脏的解决方案将有所帮助(它是API v3)

<html> 
<head> 
<style>
#over {
position: absolute;
z-index:99999;
width: 250px;
height: 600px;
opacity: 0.7;
top: 0px;
border: 2px solid black;
left: 0px;
background: white;
}
</style>

<meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
<title>Google Maps Bounds</title> 
<script src="http://code.jquery.com/jquery-1.4.4.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript"> 
var map;
var bounds;
var  overlay;
//the witdh of your overlay (probably should get it dynamically
var overlayWidth = 250;

function initialize() {
  var chicago = new google.maps.LatLng(41.875696,-87.624207);
  var myOptions = {
    zoom: 11,
    center: chicago,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  map = new google.maps.Map(document.getElementById("map_canvas"),
        myOptions);
         overlay = new google.maps.OverlayView();

    overlay.draw = function() {};

    overlay.setMap(map);


}
function addMarker() {

maywood = new google.maps.LatLng(41.8823,-87.8487);
 var marker = new google.maps.Marker({
      position: maywood, 
      map: map
  }); 
bounds = map.getBounds();

point = overlay.getProjection().fromLatLngToContainerPixel(maywood);
//point is under overlay
if (point.x<overlayWidth) {
//calculate offset by which to extend 
offset = new google.maps.Point((point.x-overlayWidth),0);
extendByX = overlay.getProjection().fromContainerPixelToLatLng(offset);
//here you might want to check if all your existing markers will fit into new bounds before applying the new bounds
newBounds = new google.maps.LatLngBounds(extendByX,bounds.getNorthEast());
map.fitBounds(newBounds);
}


}

</script> 
</head> 
<body onload="initialize()"> 
<div id="over">OVERLAY</div>
  <div id="map_canvas" style="width: 900px;height: 600px;"></div> 
<input type="button" value="Add Marker & Expand Bounds" onclick="addMarker()">
</body> 
</html>