问题
I have a map-canvas which covers the entire screen.
#map-canvas
{
height: 100%;
position: absolute;
top: 0px;
left: 0;
right: 0;
z-index: 0;
}
On top of this canvas there is a left sidebar which is translucent and the area on the right displays the marker on the map using rails model. Now when I connect my views to the son result data, some of the markers are below the sidebar but I want all the markers to adjust to the area on the right.
What is happening:
What I want:
回答1:
I presume you know map.fitBounds(bounds);
If you feed the markers as bounds, you will get your picture above. Now, imagine we have an extra point (an invisible marker) left on the map.
We will calculate where that point is supposed to be. we don't add it to the markers but we add it to bounds.
So I just wrote a function. You can choose the width of the sidebar. I set it to 0.5 (50% sidebar), see line 29. Adapt this to the value you need.
<style>
#map {
height: 400px;
}
</style>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
locations = [
[50.86721032255901,4.317024205042674],
[50.89585769377925,4.481363151385143],
[50.834376046898974,4.298433814360454],
[50.82280917273896,4.395368848158672]
];
function initialize() {
map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(locations[0][0], locations[0][1]),
zoom: 10
});
for (var i=0; i<locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][0], locations[i][1]),
map: map
})
}
setBoundsLeftSidebar(locations, 0.5);
}
/**
* @param mapFraction (float): 0.0 to 1.0 ; example: 0.6 means 40% of the map is covered by the sidebar, 60% by the map
*/
function setBoundsLeftSidebar(points, mapFraction) {
// first we want to know min and max longitude
var max = -180;
var min = 180;
// We make bounds. The bounds are the markers + an extra point on the left (we will give it a latitude of point 0), see later
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<points.length; i++) {
if(points[i][1] > max) {
max = points[i][1];
}
if(points[i][1] < min) {
min = points[i][1];
}
bounds.extend(new google.maps.LatLng(points[i][0], points[i][1]));
}
// So now we have min and max.
// we add a point to the left of min
var widthTotal = (max - min) / mapFraction;
var pointExtremeLeft = max - widthTotal;
bounds.extend(new google.maps.LatLng(points[0][0], pointExtremeLeft));
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
来源:https://stackoverflow.com/questions/32044600/google-maps-marker-only-in-a-specific-area