问题
We want something like this leaflet fitBounds in our google maps application. We saw a few examples but it doesn't worked as expected. We tried to make the div as a google maps controller, extend the bounds manually but nothing from that worked...
function zoomToBounds(polygon){
bounds = new google.maps.LatLngBounds();
$.each(polygon, function( key, latLng ) {
bounds.extend(new google.maps.LatLng(latLng.lat, latLng.lng));
});
/////////////////////////////////////////////////////////////
// We saw a solution like this, but the zooming is a problem
//
// Extend bounds with a fake point:
/////////////////////////////////////////////////////////////
/*
if (this.map.getProjection()) {
proj = this.map.getProjection();
latlng = bounds.getSouthWest();
swPoint = proj.fromLatLngToPoint(latlng);
latlng2 = proj.fromPointToLatLng({
x: swPoint.x - 10,
y: swPoint.y
});
bounds.extend(latlng2);
}*/
this.map.fitBounds(bounds);
}
回答1:
After a while I found a solution that works.
if (this.map.getProjection()) {
var offsetx = 200;
var offsety = 0;
var point1 = this.map.getProjection().fromLatLngToPoint(bounds.getSouthWest());
this.map.fitBounds(bounds);
var point2 = new google.maps.Point(
( (typeof(offsetx) == 'number' ? offsetx : 0) / Math.pow(2, this.map.getZoom()) ) || 0,
( (typeof(offsety) == 'number' ? offsety : 0) / Math.pow(2, this.map.getZoom()) ) || 0
);
var newPoint = this.map.getProjection().fromPointToLatLng(new google.maps.Point(
point1.x - point2.x,
point1.y + point2.y
));
bounds.extend(newPoint);
this.map.fitBounds(bounds);
}
jsfiddle
来源:https://stackoverflow.com/questions/28174006/google-maps-fitbounds-with-padding