MapServer WMS GetFeatureInfo (local MS4W layer)

 

Using an image WMS source with GetFeatureInfo requests

This example shows how to trigger WMS GetFeatureInfo requests on click for a MapServer WMS layer. The local mapfile used is /ms4w/apps/openlayers/examples/map/wms-server.map (data is in Spatialite format). Additionally map.forEachLayerAtPixel is used to change the mouse pointer when hovering a non-transparent pixel on the map.

<!DOCTYPE html>
<html>
  <head>
    <title>WMS GetFeatureInfo (Image Layer)</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.6.5/build/ol.js"></script>
  </head>
  <body>
    <div id="map" class="map"></div>
    <div id="info">&nbsp;</div>
    <script>
      var wmsSource = new ol.source.ImageWMS({
        url: 'http://127.0.0.1:8080/cgi-bin/mapserv.exe?MAP=C:/ms4w/apps/openlayers-4.6.5/examples/map/wms-server.map',
        params: {'LAYERS': 'countries'},
        serverType: 'mapserver',
        crossOrigin: 'anonymous'
      });

      var wmsLayer = new ol.layer.Image({
        source: wmsSource
      });

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

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

      map.on('singleclick', function(evt) {
        document.getElementById('info').innerHTML = '';
        var viewResolution = /** @type {number} */ (view.getResolution());
        var url = wmsSource.getGetFeatureInfoUrl(
            evt.coordinate, viewResolution, 'EPSG:3857',
            {'INFO_FORMAT': 'text/plain'});
        if (url) {
          document.getElementById('info').innerHTML =
              '<iframe seamless src="' + url + '"></iframe>';
        }
      });

      map.on('pointermove', function(evt) {
        if (evt.dragging) {
          return;
        }
        var pixel = map.getEventPixel(evt.originalEvent);
        var hit = map.forEachLayerAtPixel(pixel, function() {
          return true;
        });
        map.getTargetElement().style.cursor = hit ? 'pointer' : '';
      });
    </script>
  </body>
</html>