如何以编程方式缩放地图以覆盖整个世界?
答案 0 :(得分:14)
function initialize () {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
minZoom: 1
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions );
var allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(85, -180), // top left corner of map
new google.maps.LatLng(-85, 180) // bottom right corner
);
var k = 5.0;
var n = allowedBounds .getNorthEast().lat() - k;
var e = allowedBounds .getNorthEast().lng() - k;
var s = allowedBounds .getSouthWest().lat() + k;
var w = allowedBounds .getSouthWest().lng() + k;
var neNew = new google.maps.LatLng( n, e );
var swNew = new google.maps.LatLng( s, w );
boundsNew = new google.maps.LatLngBounds( swNew, neNew );
map .fitBounds(boundsNew);
}
google.maps.event.addDomListener(window, 'load', initialize);
#map {
width: 500PX;
height: 500px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
// map zoom level should be 1
答案 1 :(得分:5)
创建新地图实例时,您可以指定缩放级别。
var myOptions = {
zoom:7,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
缩放值越低,您看到的地图越多,因此值1或2应显示整个地球(取决于地图画布的大小)。创建地图后,您可以致电:
map.setZoom(8);
更改缩放级别。
答案 2 :(得分:3)
不能保证不会重复,但是通过滥用基本图块从256(缩放0)开始并且在每个增量处加倍的事实 - 您可以使用对数选择最佳缩放级别功能
function initialize () {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: Math.ceil(Math.log2($(window).width())) - 8,
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
&#13;
#map {
width: 100%;
height: 500px;
}
&#13;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
</head>
<body>
<div id="map"></div>
</body>
</html>
&#13;
答案 3 :(得分:0)
这是我喜欢使用的功能 worldViewFit :
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
minZoom: 1
};
map = new google.maps.Map(document.getElementById('officeMap'), mapOptions);
google.maps.event.addListenerOnce(map, 'idle', function() {
//Map is ready
worldViewFit(map);
});
}
function worldViewFit(mapObj) {
var worldBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(70.4043,-143.5291), //Top-left
new google.maps.LatLng(-46.11251, 163.4288) //Bottom-right
);
mapObj.fitBounds(worldBounds, 0);
var actualBounds = mapObj.getBounds();
if(actualBounds.getSouthWest().lng() == -180 && actualBounds.getNorthEast().lng() == 180) {
mapObj.setZoom(mapObj.getZoom()+1);
}
}
答案 4 :(得分:-1)
此问题的解决方案是在地图对象上使用fitBounds方法并指定适当的边界。