如何在Google Maps API中为多个矩形显示含经纬度的弹窗?
实现Google Maps矩形悬停显示经纬度弹窗的解决方案
要实现鼠标悬停在矩形上显示经纬度数据弹窗,你可以借助Google Maps的InfoWindow组件,并为每个矩形绑定鼠标悬停/移出事件。以下是修改后的完整代码:
// This example adds a red rectangle to a map. function initMap() { var map = new google.maps.Map(document.getElementById('map'), { zoom: 5, center: {lat: 51.5, lng: 15}, mapTypeId: google.maps.MapTypeId.TERRAIN }); // 初始化一个全局信息窗口实例 var infoWindow = new google.maps.InfoWindow(); var countries = [ { color: '#FF0000', minLat: 47.27, maxLat: 55.05, minLong: 5.87, maxLong: 15.03 },{ color: '#00FF00', minLat: 45.82, maxLat: 47.8, minLong: 5.97, maxLong: 10.49 },{ color: '#0000FF', minLat: 46.38, maxLat: 49.02, minLong: 9.54, maxLong: 17.16 },{ color: '#00FFFF', minLat: 48.56, maxLat: 51.03, minLong: 12.1, maxLong: 18.86 },{ color: '#FFFF00', minLat: 41.19, maxLat: 81.86, minLong: 27.9, maxLong: 170 } ]; countries.forEach(function(c) { var rectangle = new google.maps.Rectangle({ strokeColor: c.color, strokeOpacity: 0.8, strokeWeight: 2, fillColor: c.color, fillOpacity: 0.35, map: map, bounds: { north: c.minLat, south: c.maxLat, east: c.maxLong, west: c.minLong } }); // 绑定鼠标悬停事件 google.maps.event.addListener(rectangle, 'mouseover', function() { // 构造弹窗内容,展示经纬度数据 var content = ` <div> <p><strong>纬度范围:</strong> ${c.minLat} (北) ~ ${c.maxLat} (南)</p> <p><strong>经度范围:</strong> ${c.minLong} (西) ~ ${c.maxLong} (东)</p> </div> `; infoWindow.setContent(content); // 在矩形中心位置打开弹窗 infoWindow.setPosition(rectangle.getBounds().getCenter()); infoWindow.open(map); }); // 绑定鼠标移出事件,关闭弹窗 google.maps.event.addListener(rectangle, 'mouseout', function() { infoWindow.close(); }); }); }
关键修改说明
- 创建全局的
InfoWindow实例,避免重复创建多个弹窗,提升性能。 - 为每个矩形添加
mouseover事件:触发时构造包含当前矩形经纬度数据的HTML内容,设置到InfoWindow中,并在矩形中心位置打开弹窗。 - 添加
mouseout事件:鼠标移出矩形时关闭弹窗。
内容的提问来源于stack exchange,提问作者Jayesh Dahiwale
相关产品推荐
相关产品推荐

