OpenLayers 3 Beginner’s Guide

Understanding forEachFeatureAtPixel method

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>Get Features from vector</title>
    <link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />
    <link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
  </head>
  <body>
    <div id="information"></div>
    <div id="map" class="map"></div>
    <script src="../assets/ol3/js/ol-debug.js"></script>
    <script>

      var raster = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'sat'})
      });

      var selectEuropa = new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: '#ff0000',
            width: 2
        })
      });

      var defaultEuropa = new ol.style.Style({
        stroke: new ol.style.Stroke({
          color: '#0000ff',
          width: 2
        })
      });

      var vectorEuropa = new ol.layer.Vector({
        id: 'europa',
        source: new ol.source.GeoJSON({
          projection: 'EPSG:3857',
          url: '../assets/data/nutsv9_lea.geojson'
        }),
        style: defaultEuropa
      });

      var selectInteraction = new ol.interaction.Select({
        layers: function (layer) {
          return layer.get('id') == 'europa';
        },
        style: [selectEuropa]
      });

      var london = ol.proj.transform([-0.12755, 51.507222], 'EPSG:4326', 'EPSG:3857');

      var view = new ol.View({
        center: london,
        zoom: 6
      });

      var map = new ol.Map({
        target: 'map'
      });

      map.addLayer(raster);
      map.addLayer(vectorEuropa);
      map.setView(view);

      map.getInteractions().extend([selectInteraction]);

      var displayFeatureInfo = function(pixel) {
        var features = [];
        map.forEachFeatureAtPixel(pixel, function(feature, layer) {
          features.push(feature);
        });
        var container = document.getElementById('information');
        if (features.length > 0) {
          var info = [];
          for (var i = 0, ii = features.length; i < ii; ++i) {
            info.push(features[i].get('N3NM'));
          }
          container.innerHTML = info.join(', ') || '(unknown)';
        } else {
          container.innerHTML = '&nbsp;';
        }
      };

      map.on('click', function(evt) {
        var pixel = evt.pixel;
        displayFeatureInfo(pixel);
      });
    </script>
  </body>
</html>