Extend Google Maps Bounds so that div overlay doesn't cover any markers
In a Google Maps mashup I'm working on, the map is 100% wide and pretty much 100% tall and I have a horizontal transparent div that overlays the left side of the map using z-index and CSS.
When I dynamically add my markers, I start with an empty Bounds object and extend it one by one to contain the new LatLngs. Sometimes however the markers appear under my transparent div that contains other elements.
Let's say my transparent div is 250 pixels wide.
What I'd like to do is once my bounds that show all the markers are established, I'd like to extend them one more time to expand the viewport of the Google Map so that when I fit the bounds, these markers now appear at least 250 pixels away from the left border so that they are not covered by the transparent div.
I tried playing with MapProjection.fromPointToLatLng
and MapCanvasProjection.fromDivPointToLatLng
but w开发者_如何学Goasn't able to achieve predictable results.
Any advice or examples would be appreciated.
Hopefully this quick and dirty solution will help (it is 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>
精彩评论