html
<style> .ol-popup { position: absolute; background-color: white; -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2)); padding: 15px; border-radius: 10px; border: 1px solid #cccccc; bottom: 12px; left: -50px; min- 280px; } .ol-popup:after, .ol-popup:before { top: 100%; border: solid transparent; content: " "; height: 0; 0; position: absolute; pointer-events: none; } .ol-popup:after { border-top-color: white; border- 10px; left: 48px; margin-left: -10px; } .ol-popup:before { border-top-color: #cccccc; border- 11px; left: 48px; margin-left: -11px; } .ol-popup-closer { text-decoration: none; position: absolute; top: 2px; right: 8px; } .ol-popup-closer:after { content: "✖"; } </style> <div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div> <div id="allmap"> </div>
初始化
//初始化地图 //中心点 var defaults={ centerLng:0, centerLat:0 }; var closer = document.getElementById('popup-closer'); var container = document.getElementById('popup'); var content = document.getElementById('popup-content'); var popOverlay = new ol.Overlay({ element: container, autoPan: true, autoPanAnimation: { duration: 250 } }); var map = new ol.Map({ layers: [new ol.layer.Tile({ source: new ol.source.OSM() })], overlays: [popOverlay], target: opts.mapContainerId, view: new ol.View({ center: new ol.proj.fromLonLat([defaults.centerLng, defaults.centerLat]), zoom: 12 }) });
类似于marker标注
var feature = new ol.Feature({ geometry: new ol.geom.Point(ol.proj.fromLonLat([opt.lng, opt.lat])), name: "气泡框里的内容" }); feature.setStyle(new ol.style.Style({ image: new ol.style.Icon(/** @type {module:ol/style/Icon~Options} */({ anchor: [0.5, 0.96], crossOrigin: 'anonymous', src: "图标url", //img: image, //imgSize: img ? [img.width, img.height] : undefined })) })); features.push(feature); var vectorSource = new ol.source.Vector({ features: features }); var osmLayer = new ol.layer.Vector({ source: vectorSource, }); map.addLayer(osmLayer); //显示所有标注点 map.getView().fit(osmLayer.getSource().getExtent(), map.getSize()); //点击事件 map.on('click', function (evt) { var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) { return feature; }); if (feature) { var coordinates = feature.getGeometry().getCoordinates(); popOverlay.setPosition(coordinates); content.innerHTML = feature.get('name').innerHTML; } else { popOverlay.setPosition(undefined); } });