【发布时间】:2015-08-27 12:23:12
【问题描述】:
我在一个隐藏的 div 中有一张地图,按下按钮就会显示出来。我最初遇到了问题,但通过触发调整大小事件来解决它们。我现在的问题是地图没有以我初始化地图的位置为中心。
我想在 resize 或 bounds changed 事件侦听器中添加一个 map.setCenter(?) 调用,但它们似乎从未被调用。我在每一个中都设置了警报以进行测试,但没有任何反应。
编辑:根据要求提供示例...
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple markers</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#theButton {
position: absolute;
top: 0;
left: 400px;
padding: 10px;
background-color: orange;
z-index: 100;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="theButton" onclick="resizeMap();">Click Me</div>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Test Location!'
});
var getCen = map.getCenter();
var currentMapCenter = null;
google.maps.event.addListener(map, 'resize', function () {
currentMapCenter = map.getCenter();
alert("Resizing");
});
google.maps.event.addListener(map, 'bounds_changed', function () {
if (currentMapCenter) {
// react here
map.setCenter(currentMapCenter);
alert("Centering");
}
currentMapCenter = null;
});
}
function resizeMap() {
alert("Clicked");
google.maps.event.trigger(map, 'resize');
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?signed_in=true&callback=initMap"></script>
</body>
</html>
【问题讨论】:
-
请提供一个Minimal, Complete, Tested and Readable example 来证明您的问题。
-
@geocodezip 我在原始问题中包含了一个编辑,希望对您有所帮助。
-
您的示例似乎没有隐藏的 div。 fiddle
-
@geocodezip 它没有,我提供了一个简化的示例,因为发布原始代码对我来说是不切实际的。这提供了正在发生的事情的演示 - 调整大小由附加到按钮的 JS 函数触发。地图看起来不错,但似乎没有调用调整大小的侦听器。
-
您希望
google.maps.event.trigger更改mapdiv 的大小?它没有,它只是告诉 API 大小已更改,以便它可以根据新大小重新计算。
标签: javascript google-maps google-maps-api-3