How do you create tooltips (context) on OpenLayers 3 map, using standard Javascript and flat CSS. (No extra libraries)
Answer
This works on OL 3.20.1. This example assumes you already have a feature layer added to your map.
HTML
CSS
#map {
position: relative;
}
#info {
position: absolute;
z-index: 10;
background-color: black;
border: 1px solid #ccc;
color: #fff;
padding: 5px;
font-size: 18px;
top: -10em;
pointer-events: none;
}
JS
Here you need to replace feature.get('name') by whatever feature property you want to show on your popup.
var info = document.getElementById('info');
var target = document.getElementById('map');
function displayFeatureInfo(pixel) {
info.style.left = pixel[0] + 'px';
info.style.top = (pixel[1] - 50) + 'px';
var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
return feature;
});
if (feature) {
var text = feature.get('name');
info.style.display = 'none';
info.innerHTML = text;
info.style.display = 'block';
target.style.cursor = "pointer";
} else {
info.style.display = 'none';
target.style.cursor = "";
}
}
map.on('pointermove', function(evt) {
if (evt.dragging) {
info.style.display = 'none';
return;
}
var pixel = map.getEventPixel(evt.originalEvent);
displayFeatureInfo(pixel);
});
No comments:
Post a Comment