OpenLayers 3 Beginner’s Guide

Interacting with features

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>Vector Style Examples</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="map" class="map"></div>
    <div id="name" style="font-size: 24px;"></div>
    <script src="../assets/ol3/js/ol.js"></script>
    <script>
      var countries = new ol.layer.Vector({
        source: new ol.source.GeoJSON({
          projection: 'EPSG:3857',
          url: '../assets/data/countries.geojson'
        })
      });
      var center = ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857');
      var view = new ol.View({
        center: center,
        zoom: 1
      });
      var map = new ol.Map({
        target: 'map',
        layers: [countries],
        view: view
      });

      // when the user moves the mouse, get the name property
      // from each feature under the mouse and display it
      function onMouseMove(browserEvent) {
        var coordinate = browserEvent.coordinate;
        var pixel = map.getPixelFromCoordinate(coordinate);
        var el = document.getElementById('name');
        el.innerHTML = '';
        map.forEachFeatureAtPixel(pixel, function(feature) {
          el.innerHTML += feature.get('name') + '<br>';
        });
      }
      map.on('pointermove', onMouseMove);

    </script>
  </body>
</html>