百度地图多信息窗口同时显示问题

百度地图多定位情况下显示多个信息框

今天一晚上都在弄这个定位demo。多点定位,显示多点的信息内容。弄得太晚了。晚上12点了刚弄好。就不多写废话了。上图,上代码。

在这里插入图片描述
这里由于我本身业务的需求,只需要定位且只能有两个定位,所以这里我是写死了两个定位的标签。如果你有多个定位,要改成数组存放坐标信息,然后循环生成。

思路:使用label给定位加标签的方式。
直接贴代码,拿去参考。
注意要换成你自己的AK。直接复制下面的源码另存成一个html文件运行即可。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="https://api.map.baidu.com/api?type=webgl&v=1.0&ak=你的AK"></script>
    <script src="https://code.bdstatic.com/npm/jquery@1.12.4/dist/jquery.min.js"></script>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <title>demo</title>
    <style>
        body,html{
           width: 100%;
           height: 100%;
           padding: 0;
           margin: 0;
       }
       #container{
           width: 100%;
           height: 100%;
           overflow: hidden;
       }
       #result{
           position: fixed;
           top: 10px;
           right: 10px;
           padding: 0px 7px;
           min-width: 350px;
           height: 70px;
           line-height: 35px;
           background: #fff;
           box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
           border-radius: 7px;
           z-index: 99;
       }
    </style>
	 <style>

        .coordinate-panel {
		   position: fixed;
           top: 10px;
           left: 10px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.2);
            backdrop-filter: blur(4px);
            border: 1px solid rgba(255, 255, 255, 0.18);
            padding: 20px;
            width: 200px;
            text-align: center;
            transition: transform 0.3s ease;
			z-index: 99;
        }

        .coordinate-panel:hover {
            transform: translateY(-5px);
        }

        .panel-title {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 1rem;
            font-weight: 600;
        }

        .button-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .save-btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .save-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
        }

        .save-btn:active {
            transform: translateY(0);
        }

        .save-btn-1 {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .save-btn-2 {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .coordinates-display {
            margin-top: 20px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            text-align: left;
            font-size: 0.9rem;
        }

        .coordinate-item {
            margin: 8px 0;
            padding: 8px;
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .coordinate-label {
            font-weight: bold;
            color: #2c3e50;
        }

        .coordinate-value {
            color: #7f8c8d;
            font-family: monospace;
        }
		
		
        /* Toast 提示样式 */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
        }

        .toast {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            padding: 20px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 15px;
            transform: translateX(100%);
            opacity: 0;
            transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            border-left: 5px solid #4CAF50;
            min-width: 300px;
        }

        .toast.show {
            transform: translateX(0);
            opacity: 1;
        }

        .toast.success {
            border-left-color: #4CAF50;
        }

        .toast.error {
            border-left-color: #f44336;
        }

        .toast-icon.success {
            color: #4CAF50;
            font-size: 24px;
        }

        .toast-icon.error {
            color: #f44336;
            font-size: 24px;
        }

        .toast-content h4 {
            margin: 0 0 5px 0;
            color: #333;
            font-size: 1.1rem;
        }

        .toast-content p {
            margin: 0;
            color: #666;
            font-size: 0.9rem;
        }

        .toast-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #999;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        .toast-close:hover {
            background: #f0f0f0;
            color: #666;
        }


        /* 地址显示面板 */
		.address-panel {
            position: relative;
            left: 0;
            bottom: 0;
            transform: none;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            padding: 10px 10px;
            width: 100%;
            max-width: 400px;
            margin: 0 auto;
            border: 1px solid rgba(255, 255, 255, 0.3);
            transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
            z-index: 100;
        }

        .panel-content {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .location-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.2rem;
            flex-shrink: 0;
        }

        .location-info {
            flex: 1;
            min-width: 0;
        }

        .location-name {
            font-size: 1.1rem;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 3px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .location-address {
            font-size: 0.85rem;
            color: #7f8c8d;
            margin-bottom: 3px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .location-coordinates {
            font-size: 0.8rem;
            color: #95a5a6;
            font-family: monospace;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .panel-close {
            background: none;
            border: none;
            font-size: 1.2rem;
            cursor: pointer;
            color: #95a5a6;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            flex-shrink: 0;
        }

        .panel-close:hover {
            background: #f8f9fa;
            color: #2c3e50;
        }

        .show-example-btn {
            margin-top: 30px;
            padding: 12px 25px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .show-example-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        @media (max-width: 768px) {
            .address-panel {
                padding: 12px 15px;
            }
            
            .location-icon {
                width: 35px;
                height: 35px;
                font-size: 1rem;
            }
            
            .location-name {
                font-size: 1rem;
            }
            
            .location-address {
                font-size: 0.8rem;
            }
            
            .location-coordinates {
                font-size: 0.75rem;
            }
        }

        @media (max-width: 480px) {
            .panel-content {
                gap: 10px;
            }
            
            .location-icon {
                width: 32px;
                height: 32px;
            }
            
            .location-name {
                font-size: 0.95rem;
            }
        }
		
		 /* 定位按钮样式 */
        .locate-button {
            position: absolute;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: white;
            border-radius: 50%;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            z-index: 100;
        }

        .locate-button:hover {
            transform: scale(1.1);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
        }

        .locate-button:active {
            transform: scale(0.95);
        }

        .locate-button i {
            font-size: 1.5rem;
            color: #667eea;
        }

        /* 加载动画 */
        .locate-button.loading i {
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 成功提示 */
        .success-message {
            position: absolute;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(40, 167, 69, 0.9);
            color: white;
            padding: 12px 20px;
            border-radius: 8px;
            font-size: 0.9rem;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            z-index: 100;
        }

        .success-message.show {
            opacity: 1;
            visibility: visible;
            transform: translateX(-50%) translateY(10px);
        }

        @media (max-width: 768px) {
            .locate-button {
                bottom: 20px;
                right: 20px;
                width: 45px;
                height: 45px;
            }
            
            .locate-button i {
                font-size: 1.3rem;
            }
        }
    </style>
</head>
<body>

    <!-- Toast 提示容器 -->
    <div class="toast-container" id="toastContainer"></div>
	
  <div class="coordinate-panel">
        <div class="panel-title">📍 坐标保存工具</div>
        <div class="button-container">
            <button id="saveBtn1" class="save-btn save-btn-1">
                <span>💾 保存坐标一</span>
            </button>
            <button id="saveBtn2" class="save-btn save-btn-2">
                <span>💾 保存坐标二</span>
            </button>
        </div>
        
     <!--   <div class="coordinates-display">
            <div class="coordinate-item">
                <div class="coordinate-label">坐标一:</div>
                <div class="coordinate-value" id="coord1Display">未设置</div>
            </div>
            <div class="coordinate-item">
                <div class="coordinate-label">坐标二:</div>
                <div class="coordinate-value" id="coord2Display">未设置</div>
            </div>
        </div> -->
    </div>
    <div id='container'></div>
    <div id='result'>
        点击展示详细的地址:
        <div id='result_l'></div>
    </div>
	 <!-- 定位按钮 -->
        <button class="locate-button" id="locateBtn">
            <i class="fas fa-location-arrow"></i>
        </button>

        <!-- 成功提示 -->
        <div class="success-message" id="successMessage">
            已定位到当前位置
        </div>
    <script>
	
	  var point_lng_1;
	  var point_lat_1;
	  var city_1;
	  var street_1
	  var point_lng_2;
	  var point_lat_2;
	  var city_2;
	  var street_2
	  var cur_point_lng;
	  var cur_point_lat;
	  var cur_city;
	  var cur_street;
	  var zoompoint;//原点坐标
        //实例化地图
        var map = new BMapGL.Map('container');
		  //获取当前位置
		var geolocation = new BMapGL.Geolocation();
		geolocation.getCurrentPosition(function(r){
			if(this.getStatus() == BMAP_STATUS_SUCCESS){
				mk = new BMapGL.Marker(r.point);
				zoompoint = r.point;
				map.centerAndZoom(r.point, 13);

				map.addOverlay(mk);
			}else {
				alert('failed'+this.getStatus());
			}
		});
        var geoc = new BMapGL.Geocoder();
       //设置允许缩放
	   map.enableScrollWheelZoom();
	   //添加地图点击事件
        map.addEventListener('click', function(e){
            //清除地图上所有的覆盖物
            map.clearOverlays();
		//添加已经保存的坐标
		if(point_lng_1 && point_lat_1){
			var marker_1 = new BMapGL.Marker(new BMapGL.Point(point_lng_1,point_lat_1));
			//marker_1.setLabel(getNumberLabel(1));
			// 创建文本标注对象 
			var label = addressPanelLabel('①坐标一',city_1,street_1,point_lng_1, point_lat_1);
			marker_1.setLabel(label);

			map.addOverlay(marker_1);
				// 创建圆
			var circle_1 = new BMapGL.Circle(
			new BMapGL.Point(point_lng_1,point_lat_1),150,{
				strokeColor: '#4595d5',
				strokeWeight: 6,
				strokeOpacity: 0.5
			});
			map.addOverlay(circle_1);

		}
		if(point_lng_2 && point_lat_2){
			var marker_2 = new BMapGL.Marker(new BMapGL.Point(point_lng_2, point_lat_2));

				// 创建圆
			var circle_2 = new BMapGL.Circle(
			new BMapGL.Point(point_lng_2, point_lat_2),150,{
				strokeColor: '#4595d5',
				strokeWeight: 6,
				strokeOpacity: 0.5
			});
			var label = addressPanelLabel('②坐标二',city_2,street_2,point_lng_2, point_lat_2);
			marker_2.setLabel(label);

			map.addOverlay(marker_2);

			map.addOverlay(circle_2);


		}
		
            console.log(e);
            var pt = e.latlng;
            var marker = new BMapGL.Marker(new BMapGL.Point(pt.lng, pt.lat));
            map.addOverlay(marker);
		//临时存放当前点击坐标	
		cur_point_lng = pt.lng;
		cur_point_lat = pt.lat;
			
		// 创建圆
		var circle = new BMapGL.Circle(
		new BMapGL.Point(pt.lng, pt.lat),150,{
			strokeColor: '#4595d5',
			strokeWeight: 6,
			strokeOpacity: 0.5
		});
		map.addOverlay(circle);
		
			
            geoc.getLocation(pt, function(rs){
                var addComp = rs.addressComponents;
                $('#result_l').text(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
				cur_city = addComp.province + addComp.city ;
				cur_street = addComp.district +addComp.street + addComp.streetNumber;
				cur_point = formatCoordinate(pt.lng,pt.lat); 
				marker.openInfoWindow(addressPanel(cur_city,cur_street,cur_point));
            })
        })
		
	
		// 保存坐标一按钮事件
        document.getElementById('saveBtn1').onclick = function(e) {
            if (cur_point_lng == null && cur_point_lat == null) {
                showToast("请先在地图选点", "error");
            } else {
                point_lng_1 = cur_point_lng;
                point_lat_1 = cur_point_lat;
			city_1 =	cur_city;
			street_1 = cur_street;
			showToast("坐标一保存成功!");
            }
        };

        // 保存坐标二按钮事件
        document.getElementById('saveBtn2').onclick = function(e) {
            if (cur_point_lng == null && cur_point_lat == null) {
                 showToast("请先在地图选点", "error");
            } else {
                point_lng_2 = cur_point_lng;
                point_lat_2 = cur_point_lat;
			city_2 =	cur_city;
			street_2 = cur_street;
		   showToast("坐标二保存成功!");
            }
        };
		
		//生成数字的文本标记,1 ,2 ,3这种
		function getNumberLabel(number) {
			var offsetSize = new BMapGL.Size(0, 0);

			var labelStyle = {
				color: "#fff",
				backgroundColor: "0.05",
				border: "0"
			};
 
			//不同数字长度需要设置不同的样式。
			switch((number + '').length) {
				case 1:
					labelStyle.fontSize = "14px";
					offsetSize = new BMapGL.Size(-5, -24);
					break;
				case 2:
					labelStyle.fontSize = "12px";
					offsetSize = new BMapGL.Size(-5, -24);
					break;
				case 3:
					labelStyle.fontSize = "10px";
					offsetSize = new BMapGL.Size(-2, 4);
					break;
				default:
					break;
			}
 
			var label = new BMapGL.Label(number, {
				offset: offsetSize 
			});
			label.setStyle(labelStyle);
			return label;
		}
		
		function addressPanel(cur_city,cur_street,cur_point) {
		//添加信息窗口
				var opts = {
						width: 250, // 信息窗口宽度
						height: 80, // 信息窗口高度
						title: "<div class='location-name' id='locationName'>" // 修正:‘location-name‘ -> 'location-name'
								+ cur_city +
								"</div>" , // 信息窗口标题
					}
				let sContent =
					
					"<div class='address-panel' >" +
						"<div class='panel-content'>" +
							"<div class='location-icon'>" + // 修正:'ocation' -> 'location' 且改为英文引号
								"<i class='fas fa-map-marker-alt'></i>" +
							"</div>" +
							"<div class='location-info'>" + // 修正:’ocation-info‘ -> 'location-info'
								"<div class='location-address' id='fullAddress'>" + cur_street + "</div>" + // 修正:'ocation-address' -> 'location-address'
								"<div class='location-coordinates' id='coordinates'>" + cur_point+ "</div>" +
							"</div>" +
						"</div>" +
					"</div>";
				let infoWindow = new BMapGL.InfoWindow(sContent,opts);
				infoWindow.setContent(sContent);
				return infoWindow;
		}
		function addressPanelLabel(cur_label,cur_city,cur_street,point_lng_1, point_lat_1) {
		//添加信息窗口
			var opts = {
				position: new BMapGL.Point(point_lng_1, point_lat_1), // 指定文本标注所在的地理位置
				offset: new BMapGL.Size(-100, -145) // 设置文本偏移量
			};
				let sContent =
					
					"<div class='address-panel' style='box-shadow::0 4px 8px rgba(128, 128, 128, 0.5)' >" +
						"<div class='panel-content'>" +
							"<div class='location-icon'>" + // 修正:'ocation' -> 'location' 且改为英文引号
								"<i class='fas fa-map-marker-alt'></i>" +
							"</div>" +
							"<div class='location-info'>" + // 修正:’ocation-info‘ -> 'location-info'
								"<div class='location-name' id='locationName'>" // 修正:‘location-name‘ -> 'location-name'
								+ cur_label +
								"</div>" +
								"<div class='location-address' id='fullAddress'>" +cur_city+ cur_street + "</div>" + // 修正:'ocation-address' -> 'location-address'
								"<div class='location-coordinates' id='coordinates'>" + formatCoordinate(point_lng_1, point_lat_1)+ "</div>" +
							"</div>" +
						"</div>" +
						"<img style='z-index: 1; position: absolute; width: 58px; height: 31px; left: 96px; bottom: -30px; top: 87px;' src='https://webmap0.bdimg.com/image/api/iw_tail.png'>"+
					"</div>";
				let label = new BMapGL.Label(sContent,opts);
				label.setStyle({
					borderRadius: '5px',
					border:'1px solid rgb(221,221,221)'
				});
				return label;
		}
		//提示信息
		// Toast 提示函数
        function showToast(message, type = 'success') {
            const toastContainer = document.getElementById('toastContainer');
            
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            
            const icon = document.createElement('div');
            icon.className = `toast-icon ${type}`;
            icon.innerHTML = type === 'success' ? '<i class="fas fa-check-circle"></i>' : '<i class="fas fa-exclamation-circle"></i>';
            
            const content = document.createElement('div');
            content.className = 'toast-content';
            content.innerHTML = `
                <h4>${type === 'success' ? '保存成功' : '保存失败'}</h4>
                <p>${message}</p>
            `;
            
            const closeBtn = document.createElement('button');
            closeBtn.className = 'toast-close';
            closeBtn.innerHTML = '&times;';
            closeBtn.onclick = function() {
                hideToast(toast);
            };
            
            toast.appendChild(icon);
            toast.appendChild(content);
            toast.appendChild(closeBtn);
            
            toastContainer.appendChild(toast);
            
            // 显示动画
            setTimeout(() => {
                toast.classList.add('show');
            }, 10);
            
            // 3秒后自动隐藏
            setTimeout(() => {
                hideToast(toast);
            }, 3000);
        }

        function hideToast(toast) {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 400);
        }

	//格式化经纬度坐标
	function formatCoordinate(lng, lat) {
		const lngFormatted = lng.toFixed(4) + "°E";
		const latFormatted = lat.toFixed(4) + "°N";
		return lngFormatted + ", " + latFormatted;
    }
	//回到当前位置
	// 获取DOM元素
        const locateBtn = document.getElementById('locateBtn');
        const successMessage = document.getElementById('successMessage');

        // 定位功能
        locateBtn.addEventListener('click', function() {
			map.centerAndZoom(zoompoint, 13);
            // 添加加载状态
            this.classList.add('loading');
            
            // 模拟定位过程
            setTimeout(() => {
                // 移除加载状态
                this.classList.remove('loading');
                
                // 显示成功提示
                successMessage.classList.add('show');
                
                // 3秒后隐藏提示
                setTimeout(() => {
                    successMessage.classList.remove('show');
                }, 3000);
                
                console.log('已定位到当前位置');
            }, 1500);
        });
    </script>
</body>
</html>

点赞关注不迷路,来自贵州久远银海的顶级游资!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值