openlayers-3

Openlayers 3. How to make tootlip for feature


Now I'm moving my project from openlayers 2 to openlayers 3. Unfortunately I can't find how to show title (tooltip) for feature. In OL2 there was a style named graphicTitle. Could you give me advice how to implement tooltip on OL3?


Solution

  • This is example from ol3 developers. jsfiddle.net/uarf1888/

    var tooltip = document.getElementById('tooltip');
    var overlay = new ol.Overlay({
      element: tooltip,
      offset: [10, 0],
      positioning: 'bottom-left'
    });
    map.addOverlay(overlay);
    
    function displayTooltip(evt) {
      var pixel = evt.pixel;
      var feature = map.forEachFeatureAtPixel(pixel, function(feature) {
        return feature;
      });
      tooltip.style.display = feature ? '' : 'none';
      if (feature) {
        overlay.setPosition(evt.coordinate);
        tooltip.innerHTML = feature.get('name');
      }
    };
    
    map.on('pointermove', displayTooltip);