Google Maps API 是一种允许开发者在网页中嵌入 Google 地图功能的 JavaScript API。当与前端框架(如 Bootstrap)结合使用时,可能会出现地图覆盖或遮挡其他页面元素的问题。
position: fixed
,而地图容器可能没有正确处理这种布局/* 确保导航栏的 z-index 高于地图容器 */
.navbar {
position: fixed;
width: 100%;
z-index: 1000; /* 高于地图的默认 z-index */
}
/* 地图容器样式 */
.map-container {
position: relative;
z-index: 1;
margin-top: 56px; /* 导航栏高度 */
}
// 初始化地图时考虑导航栏高度
function initMap() {
const navbarHeight = document.querySelector('.navbar').offsetHeight;
const map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
// 调整地图容器上边距
document.getElementById('map').style.marginTop = `${navbarHeight}px`;
}
<div class="container-fluid p-0">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<!-- 导航栏内容 -->
</nav>
<div id="map" class="map-container"></div>
</div>
.map-container {
height: calc(100vh - 56px); /* 视口高度减去导航栏高度 */
width: 100%;
}
<!DOCTYPE html>
<html>
<head>
<title>Google Maps with Fixed Navbar</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.navbar {
position: fixed;
width: 100%;
z-index: 1000;
}
.map-container {
height: calc(100vh - 56px);
width: 100%;
margin-top: 56px;
position: relative;
z-index: 1;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">My App</a>
<!-- 其他导航项 -->
</div>
</nav>
<div id="map" class="map-container"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
<script>
function initMap() {
const map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
</body>
</html>
这种解决方案适用于:
没有搜到相关的文章