在 jQuery Mobile 应用中集成 Google Maps 时,经常会遇到地图容器 div 在滑动时大小不正确的问题。这是由于 jQuery Mobile 的页面过渡动画和 Google Maps 的尺寸计算机制之间的交互问题导致的。
$(document).on("pagecontainershow", function() {
// 初始化地图
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
// 监听页面过渡完成事件
$(window).on("resize", function() {
google.maps.event.trigger(map, "resize");
map.setCenter({lat: -34.397, lng: 150.644});
});
});
$(document).on("pageshow", "#map-page", function() {
// 确保地图容器已完全显示
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(center);
}, 300);
});
确保地图容器有明确的尺寸:
#map-canvas {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
$(window).on("orientationchange", function() {
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery Mobile with Google Maps</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
<style>
#map-page, #map-canvas {
width: 100%;
height: 100%;
padding: 0;
}
#map-canvas {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
</head>
<body>
<div data-role="page" id="map-page">
<div data-role="header">
<h1>Google Maps</h1>
</div>
<div role="main" class="ui-content">
<div id="map-canvas"></div>
</div>
</div>
<script>
var map, center = {lat: -34.397, lng: 150.644};
$(document).on("pagecontainershow", function() {
// 初始化地图
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: center,
zoom: 8
});
// 监听各种可能导致尺寸变化的事件
$(window).on("resize orientationchange", function() {
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(center);
}, 300);
});
});
// 页面显示后触发一次重绘
$(document).on("pageshow", "#map-page", function() {
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(center);
}, 500);
});
</script>
</body>
</html>
这种解决方案适用于:
通过以上方法,可以确保 Google Maps 在 jQuery Mobile 应用中始终正确显示,无论用户如何滑动或旋转设备。
没有搜到相关的文章