OpenLayers 3 Beginner’s Guide

Understanding getGetFeatureInfoUrl method

Open sample in a new windows

<!doctype html>
<html>
  <head>
    <title>GetFeatureInfo</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.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>

    var wms_layer = new ol.layer.Tile({
      source: new ol.source.TileWMS({
        url: 'http://demo.boundlessgeo.com/geoserver/wms',
        params: {'LAYERS': 'ne:ne'}
      })
    });

    var view = new ol.View({
        center: [0, 0],
        zoom: 1
    });

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

    var viewProjection = view.getProjection();
    var viewResolution = view.getResolution();

    var container = document.getElementById('information');

    map.on('click', function(evt) {
      var url = wms_layer.getSource().getGetFeatureInfoUrl(
          evt.coordinate, viewResolution, viewProjection,
          {'INFO_FORMAT': 'text/javascript',
           'propertyName': 'formal_en'});
      if (url) {
        var parser = new ol.format.GeoJSON();
        $.ajax({
          url: url,
          dataType: 'jsonp',
          jsonpCallback: 'parseResponse'
        }).then(function(response) {
          var result = parser.readFeatures(response);
          if (result.length) {
            var info = [];
            for (var i = 0, ii = result.length; i < ii; ++i) {
              info.push(result[i].get('formal_en'));
            }
            container.innerHTML = info.join(', ');
          } else {
            container.innerHTML = '&nbsp;';
          }
        });
      }
    });

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