标题popup 动态描点位置,防止内容遮盖
functionqueryFeatures(e){constfeatures=window.map.queryRenderedFeatures?window.map.queryRenderedFeatures(e.point,{if(!features||!features.length){ElMessage({message:"未查询到相关要素",type:"warning",});return};constfeature=features[0];constproperties=feature.properties||{};constpopupTitle=`<div style="padding:8px;color:#fff;border-bottom:1px solid #ccc;">元素属性</div>`;letpopupContent='<div class="attr-list style="font-size:13px">';// 过滤出有意义的属性键constkeys=Object.keys(properties||{}).filter((k)=>properties[k]!==null&&properties[k]!==undefined&&properties[k]!=="");if(keys.length===0){// 无属性时展示提示与几何摘要popupContent+=`<div style="padding:8px;color:#fff">该要素无属性</div>`;constgeom=feature.geometry||{};if(geom.type){popupContent+=`<div style="padding:6px 8px;color:#fff">类型:${geom.type}</div>`;try{if(Array.isArray(geom.coordinates)){// 简单统计坐标点数量(对不同几何类型做基本处理)letcount=0;if(geom.type==="Point")count=1;elseif(geom.type==="LineString")count=geom.coordinates.length;elseif(geom.type==="Polygon")count=(geom.coordinates[0]||[]).length;elsecount=JSON.stringify(geom.coordinates).length;popupContent+=`<div style="padding:6px 8px;color:#fff">坐标点数量:${count}</div>`;}}catch(err){// 忽略统计错误}}}else{popupContent=``;// 有属性时按 key-value 显示keys.forEach(([key])=>{});// 清空内容keys.forEach((key)=>{constvalue=properties[key];popupContent+=`<div style="margin:6px;display:flex;align-items:center;"> <strong style="display:inline-block;min-width:90px;color:#fff">${key}:</strong> <span style="color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:inline-block;max-width:calc(100% - 110px);" title="${String(value)}">${String(value)}</span> </div>`;});}popupContent+="</div>";letpopupContentBox=`${popupTitle}<div class="mapboxgl-popup-content">${popupContent}</div>`;// 在创建 Popup 前判断constpoint=window.map.project(e.lngLat);// 转为屏幕像素坐标constmapHeight=window.map.getContainer().offsetHeight;constmapWidth=window.map.getContainer().offsetWidth;constvDir=point.y>mapHeight/2?'bottom':'top';consthDir=point.x>mapWidth/2?'right':'left';constanchor=`${vDir}-${hDir}`;// 例如: 'bottom-right', 'top-left'newcompassengine.Popup({closeButton:true,closeOnClick:true,offset:15,anchor:anchor,}).setLngLat(e.lngLat).setHTML(popupContentBox).addTo(window.map);}