[英]Google Maps Javascript - Resize event listener not being called
我在一個隱藏的div中有一張地圖,通過按一下按鈕即可顯示出來。 我最初遇到問題,但是通過觸發調整大小事件來解決它們。 現在的問題是,地圖不以初始化地圖的位置為中心。
我想將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>
我已經對您的代碼進行了更深入的測試,以這種方式(在函數initMap局部作用域之外的窗口作用域中),var map
更改聲明的作用域存在問題
<script>
var map;
function initMap() {
var myLatLng = {lat: 51.320151, lng: -0.555658};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
........
......
否則,地圖將無法在其他功能中正確引用,例如:
function resizeMap() {
google.maps.event.trigger(map, 'resize');
在此函數中,如果您不更改,則不會引用var聲明映射,並且不會觸發任何操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.