var map;
function myFitBounds(myMap, bounds) {
myMap.fitBounds(bounds);
var overlayHelper = new google.maps.OverlayView();
overlayHelper.draw = function() {
if (!this.ready) {
var projection = this.getProjection(),
zoom = getExtraZoom(projection, bounds, myMap.getBounds());
if (zoom > 0) {
myMap.setZoom(myMap.getZoom() + zoom);
}
this.ready = true;
google.maps.event.trigger(this, 'ready');
}
};
overlayHelper.setMap(myMap);
}
// LatLngBounds b1, b2 -> zoom increment
function getExtraZoom(projection, expectedBounds, actualBounds) {
var expectedSize = getSizeInPixels(projection, expectedBounds),
actualSize = getSizeInPixels(projection, actualBounds);
if (Math.floor(expectedSize.x) == 0 || Math.floor(expectedSize.y) == 0) {
return 0;
}
var qx = actualSize.x/expectedSize.x;
var qy = actualSize.y/expectedSize.y;
var min = Math.min(qx, qy);
if (min < 1) {
return 0;
}
return Math.floor(Math.log(min)/Math.log(2) /* = log2(min) */);
}
// LatLngBounds bnds -> height and width as a Point
function getSizeInPixels(projection, bounds) {
var sw = projection.fromLatLngToContainerPixel(bounds.getSouthWest());
var ne = projection.fromLatLngToContainerPixel(bounds.getNorthEast());
return new google.maps.Point(Math.abs(sw.y - ne.y), Math.abs(sw.x - ne.x));
}
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
bounds = new google.maps.LatLngBounds();
var extendPoint1 = new google.maps.LatLng(35.491823,6.626860999999963);
var extendPoint2 = new google.maps.LatLng(47.09192,18.520579999999995);
new google.maps.Marker({position: extendPoint1,map: map});
new google.maps.Marker({position: extendPoint2,map: map});
bounds.extend(extendPoint1);
bounds.extend(extendPoint2);
myFitBounds(map,bounds);
//map.fitBounds(bounds);
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<div id="map-canvas"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places&callback=initialize"></script>
我試過這種方法,但我得到了額外的變焦問題,現在我發現有錯誤計算解決方案#經度6,例如,當邊界是sw(-28.599535437631257,179.61766330196713)和ne(40.60039691341636,-14.684176724750273)它增加了邊界,我試圖找出如何解決它。謝謝 – Charles