信息窗口(InfoWindow)是Google Maps API中用于在地图上显示附加信息的浮动面板。它可以包含HTML内容,并且可以动态更新。
原因:
解决方案:
// 确保地图完全加载后再创建信息窗口
google.maps.event.addListener(map, 'tilesloaded', function() {
var infowindow = new google.maps.InfoWindow({
content: '内容加载完成'
});
infowindow.open(map, marker);
});
原因:
解决方案:
// 先获取现有内容,再更新
var infowindow = new google.maps.InfoWindow();
var currentContent = '初始内容';
function updateContent(newContent) {
currentContent = newContent;
infowindow.setContent(currentContent);
// 不需要重新打开窗口
}
原因:
解决方案:
// 为每个标记创建独立的信息窗口
markers.forEach(function(marker) {
var infowindow = new google.maps.InfoWindow({
content: marker.getTitle()
});
marker.addListener('click', function() {
// 关闭其他信息窗口
closeAllInfoWindows();
infowindow.open(map, marker);
});
});
function closeAllInfoWindows() {
// 实现关闭所有信息窗口的逻辑
}
<!DOCTYPE html>
<html>
<head>
<title>动态信息窗口示例</title>
<style>
#map {
height: 400px;
width: 100%;
}
.info-window-content {
padding: 10px;
font-family: Arial, sans-serif;
}
.info-title {
font-weight: bold;
margin-bottom: 5px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7128, lng: -74.0060},
zoom: 12
});
// 创建标记
var marker = new google.maps.Marker({
position: {lat: 40.7128, lng: -74.0060},
map: map,
title: '纽约市'
});
// 创建信息窗口
var infowindow = new google.maps.InfoWindow({
content: '<div class="info-window-content">' +
'<div class="info-title">加载中...</div>' +
'<div id="dynamic-content">请稍候</div>' +
'</div>'
});
// 点击标记时打开信息窗口
marker.addListener('click', function() {
infowindow.open(map, marker);
// 模拟动态数据加载
setTimeout(function() {
var dynamicContent = document.createElement('div');
dynamicContent.innerHTML = '实时数据: ' + new Date().toLocaleTimeString();
// 动态更新内容
var contentDiv = document.getElementById('dynamic-content');
if(contentDiv) {
contentDiv.innerHTML = '';
contentDiv.appendChild(dynamicContent);
}
}, 1000);
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
function loadAsyncContent(marker, infowindow) {
fetch('/api/location-data?id=' + marker.id)
.then(response => response.json())
.then(data => {
infowindow.setContent(formatContent(data));
})
.catch(error => {
infowindow.setContent('加载失败: ' + error.message);
});
}
var infowindow = new google.maps.InfoWindow({
content: '<div class="custom-infowindow">自定义内容</div>',
maxWidth: 300
});
@media (max-width: 600px) {
.gm-style-iw {
max-width: 200px !important;
}
}
通过以上方法和技巧,您可以充分利用Google Maps API的动态信息窗口功能,创建丰富、交互性强的地图应用。
没有搜到相关的文章