OpenLayers 3 Beginner’s Guide

Adding the select interaction

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>Flickr Search</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>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="../assets/ol3/js/ol-debug.js"></script>
    <script>

    var vectorSource = new ol.source.KML({
      url: '../assets/data/flickr_data.kml',
      projection: 'EPSG:3857'
    });

    // a cluster source can group photos that are too close
    var clusterSource = new ol.source.Cluster({
      source: vectorSource,
      distance: 40
    });

    var cache = {};

    // this function computes a circle style
    // based on the size of a cluster
    // the style is cached.
    function getCircleStyle(size) {
      var key = 'circle' + size;
      if (!cache[key]) {
        cache[key] = new ol.style.Style({
          image: new ol.style.Circle({
            radius: 8 + size,
            fill: new ol.style.Fill({
              color: 'rgb(97, 151, 255)'
            }),
            stroke: new ol.style.Stroke({
              color: 'white',
              width: 2
            })
          })
        });
      }
      return cache[key];
    }

    // this function computes a text style
    // based on the size of a cluster
    // the style is cached
    function getTextStyle(text) {
      var key = 'text' + text;
      if (!cache[key]) {
        cache[key] = new ol.style.Style({
          text: new ol.style.Text({
            font: '10px sans-serif',
            text: text,
            textBaseline: 'alphabetic',
            offsetY: 4,
            fill: new ol.style.Fill({
              color: 'white'
            })
          })
        });
      }
      return cache[key];
    }

    // the style function for the cluster layer combines
    // a circle and a text style based on the size of the cluster
    function clusterStyle(feature, resolution) {
      var size = feature.get('features').length;
      var pointStyle = getCircleStyle(size);
      var textStyle = getTextStyle(size.toString());
      return [pointStyle, textStyle];
    }

    var vectorLayer = new ol.layer.Vector({
      source: clusterSource,
      style: clusterStyle
    });

    var layer = new ol.layer.Tile({
      source: new ol.source.OSM()
    });

    var center = ol.proj.transform([0,0], 'EPSG:4326', 'EPSG:3857');

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

    var map = new ol.Map({
      target: 'map',
      layers: [layer, vectorLayer],
      view: view
    });

    var select = new ol.interaction.Select({
      layers: [vectorLayer]
    });

    map.addInteraction(select);
    </script>
  </body>
</html>