[GIS] OpenLayers 3.10.1 – Feature Popup

mouse positionopenlayerspopup

I saw many examples of Feature Popup activated when the cursor is moved over a feature for OpenLayers 2.0 but none for OpenLayers 3.0.

Does anyone know how to do the following : http://jorix.github.io/OL-FeaturePopups/examples/feature-popups.html on OpenLayers 3.0 ?

Best Answer

This works on OL 3.10.1. This example assumes you already have a feature layer added to your map and are using bootstrap and Jquery.

For a solution without Jquery and Bootstrap see : OpenLayers 3 - Feature Popup without Jquery/Bootstrap

HTML

<div id="map" class="map"><div id="info"></div></div> 

CSS

#map {
  position: relative;
}

#info {
  position: absolute;
  height: 1px;
  width: 1px;
  z-index: 100;
}

.tooltip.in {
  opacity: 1;
  filter: alpha(opacity=100);
}

.tooltip.top .tooltip-arrow {
  border-top-color: white;
}

.tooltip-inner {
  border: 2px solid white;
}

JS

Here you need to replace feature.get('id') by whatever feature property you want to show on your popup (example: feature.get('name')).

var info = $('#info');
info.tooltip({
    animation: false,
    trigger: 'manual'
});

var displayFeatureInfo = function(pixel) {
    info.css({
        left: pixel[0] + 'px',
        top: (pixel[1] - 15) + 'px'
    });
    var feature = map.forEachFeatureAtPixel(pixel, function(feature, layer) {
        return feature;
    });
    if (feature) {
        info.tooltip('hide')
            .attr('data-original-title', feature.get('id'))
            .tooltip('fixTitle')
            .tooltip('show');
    } else {
        info.tooltip('hide');
    }
};

map.on('pointermove', function(evt) {
    if (evt.dragging) {
        info.tooltip('hide');
        return;
    }
    displayFeatureInfo(map.getEventPixel(evt.originalEvent));
});
Related Question