OpenLayers 3 Beginner’s Guide

Handling selection events

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>
    <div id="photo-info"></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 flickrSource = new ol.source.Vector();

    var cache = {};

    function photoStyle(feature, scale) {
      var url = feature.get('url');
      var key = scale + url;
      if (!cache[key]) {
        cache[key] = new ol.style.Style({
          image: new ol.style.Icon({
            scale: scale,
            src: url
          })
        });
      }
      return cache[key];
    }

    function flickrStyle(feature) {
      return [photoStyle(feature, 0.10)];
    }

    function selectedStyle(feature) {
      return [photoStyle(feature, 0.50)];
    }

    var flickrLayer = new ol.layer.Vector({
      source: flickrSource,
      style: flickrStyle
    });

    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, flickrLayer],
      view: view
    });

    // create a Select interaction and add it to the map
    var select = new ol.interaction.Select({
      layers: [flickrLayer],
      style: selectedStyle
    });
    map.addInteraction(select);

    // use the features Collection to detect when a feature is selected,
    // the collection will emit the add event
    var selectedFeatures = select.getFeatures();
    selectedFeatures.on('add', function(event) {
      var feature = event.target.item(0);
      var url = feature.get('url');
      // put the url of the feature into the photo-info div
      $('#photo-info').html(url);
    });

    // when a feature is removed, clear the photo-info div
    selectedFeatures.on('remove', function(event) {
      $('#photo-info').empty();
    });

    function successHandler(data) {
      var transform = ol.proj.getTransform('EPSG:4326', 'EPSG:3857');
      data.items.forEach(function(item) {
        var feature = new ol.Feature(item);
        feature.set('url', item.media.m);
        var coordinate = transform([parseFloat(item.longitude), parseFloat(item.latitude)]);
        var geometry = new ol.geom.Point(coordinate);
        feature.setGeometry(geometry);
        flickrSource.addFeature(feature);
      });
    }

    $.ajax({
      url: '../assets/data/flickr_data.json',
      dataType: 'jsonp',
      jsonpCallback: 'jsonFlickrFeed',
      success: successHandler
    });

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