【发布时间】:2015-01-16 07:31:48
【问题描述】:
我正在尝试将 map.fitBounds(bounds) 方法绑定到窗口调整大小事件,但不幸的是没有成功。也许你有想法?
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script src="http://www.mysite.url/label.js"></script>
<script>
var bounds = new google.maps.LatLngBounds(null);
function initialize() {
var mapOptions = {
panControl: true,
scaleControl: false,
overviewMapControl: false,
zoomControl: true,
mapTypeControl: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.HYBRID,
center: { lat: 0.0, lng: 40.0},
zoom: 2
};
var destinations = [
{lat:13.7246005, lng:100.6331108, myTitle:'Bangkok'},
{lat:8.722049, lng:98.23421, myTitle:'Khao Lak'},
{lat:1.3146631, lng:103.8454093, myTitle:'Singapore'},
{lat:-36.8630231, lng:174.8654693, myTitle:'Auckland'},
{lat:34.0204989, lng:-118.4117325, myTitle:'Los Angeles'},
{lat:25.782324, lng:-80.2310801, myTitle:'Miami'}
];
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var image = {
url: 'plane-icon-medium.png',
size: new google.maps.Size(24, 24),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(12, 12)
};
var flightPath = new google.maps.Polyline({
path: destinations,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
for (var i = 0; i < destinations.length; i++) {
var myTitle = destinations[i].myTitle;
var myLatLng = new google.maps.LatLng(destinations[i].lat, destinations[i].lng);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: 'test',
text: myTitle,
});
var label = new Label({
map: map
});
label.bindTo('position', marker, 'position');
label.bindTo('text', marker, 'text');
bounds.extend(marker.position);
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
var bounds = map.getBounds();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
map.fitBounds(bounds);
});
</script>
<div id="map_canvas"></div>
不幸的是,这在某种程度上不起作用。当我调整窗口大小时,地图既不会重新居中,也不会“缩放”以使所有标记(即边界)适合新窗口。
感谢和最好的问候, 克莱曼
【问题讨论】:
-
map变量的范围... 定义var map功能失效,使其成为全局变量。在函数中只需使用map = new google.maps.Map(...)。 -
具体来说,在您声明
var bounds的位置旁边声明var map -
Adam 和 skobaljic 所说的。 Working fiddle
-
你也可以反过来。将 addDomListener(window, "resize" 放在 initialize 中。然后您可以将所有变量保留在本地。在这种情况下,任何需要 'map' 的函数都应该在 initialize 中定义。jsfiddle.net/w1dv62zb/2
-
好的,完成了。非常感谢!!