Atlaslog
Atlaslog / Examples / OpenLayers / Getfeatureinfo Layers
OpenLayers · Runnable Example

Getfeatureinfo Layers

Runnable OpenLayers example: Getfeatureinfo Layers. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-getfeatureinfo-layers.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-getfeatureinfo-layers.html
<!--
  示例:多图层像元查询
  要点:一次点击反查三份同名格网栅格,逐个图层返回属性值
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>多图层像元查询</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif;color:#16181d}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:14px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:5px;align-items:center;cursor:pointer}
  #out{font-family:ui-monospace,Menlo,Consolas,monospace;color:#16181d}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label><input type="checkbox" id="cb-pop" checked> 人口密度</label>
  <label><input type="checkbox" id="cb-green" checked> 绿地率</label>
  <label><input type="checkbox" id="cb-temp"> 地表温度</label>
  <span id="out">点击地图读取三层数值</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';
  if (!window.ol) {
    document.getElementById('map').textContent = 'OpenLayers 加载失败,请检查 cdn.jsdelivr.net 是否可访问';
    return;
  }

  var N = 96;
  var bbox = [116.20, 39.75, 116.62, 40.05];
  var extent = ol.proj.transformExtent(bbox, 'EPSG:4326', 'EPSG:3857');

  function norm(row, col, phase) {
    var u = col / N, v = 1 - row / N;
    return 0.5 + 0.3 * Math.sin(u * 6.2 + phase) * Math.cos(v * 5.1 - phase)
      + 0.12 * Math.sin((u + v) * 9.3 + phase * 2);
  }

  /* 三个指标共用一套格网,取值函数同时服务于着色与查询 */
  var metrics = {
    pop: {
      label: '人口密度',
      unit: '人/km²',
      value: function (row, col) { return Math.round(1800 + norm(row, col, 0.4) * 16000); },
      color: function (t) { return [Math.round(40 + t * 210), Math.round(110 + t * 90), Math.round(220 - t * 150)]; }
    },
    green: {
      label: '绿地率',
      unit: '%',
      value: function (row, col) { return Math.round(4 + norm(row, col, 1.9) * 46); },
      color: function (t) { return [Math.round(230 - t * 200), Math.round(240 - t * 60), Math.round(210 - t * 170)]; }
    },
    temp: {
      label: '地表温度',
      unit: '℃',
      value: function (row, col) { return Math.round((22 + norm(row, col, 3.1) * 14) * 10) / 10; },
      color: function (t) { return [Math.round(250 - t * 60), Math.round(230 - t * 170), Math.round(200 - t * 160)]; }
    }
  };

  function imageURLOf(key) {
    var m = metrics[key];
    var c = document.createElement('canvas');
    c.width = c.height = N;
    var ctx = c.getContext('2d');
    var img = ctx.createImageData(N, N);
    for (var row = 0; row < N; row++) {
      for (var col = 0; col < N; col++) {
        var t = Math.max(0, Math.min(1, norm(row, col, key === 'pop' ? 0.4 : key === 'green' ? 1.9 : 3.1)));
        var rgb = m.color(t);
        var i = (row * N + col) * 4;
        img.data[i] = rgb[0];
        img.data[i + 1] = rgb[1];
        img.data[i + 2] = rgb[2];
        img.data[i + 3] = key === 'green' ? 170 : 190;
      }
    }
    ctx.putImageData(img, 0, 0);
    return c.toDataURL('image/png');
  }

  var layers = {};
  Object.keys(metrics).forEach(function (key, idx) {
    layers[key] = new ol.layer.Image({
      visible: key !== 'temp',
      opacity: 0.85,
      zIndex: 10 + idx,
      source: new ol.source.ImageStatic({
        url: imageURLOf(key),
        imageExtent: extent,
        projection: 'EPSG:3857'
      })
    });
  });

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
      layers.pop, layers.green, layers.temp
    ],
    view: new ol.View({ center: ol.proj.fromLonLat([116.40, 39.90]), zoom: 10 }),
    controls: ol.control.defaults.defaults({ rotate: false })
  });

  map.on('singleclick', function (evt) {
    var lonlat = ol.proj.toLonLat(evt.coordinate);
    var fx = (lonlat[0] - bbox[0]) / (bbox[2] - bbox[0]);
    var fy = (bbox[3] - lonlat[1]) / (bbox[3] - bbox[1]);

    if (fx < 0 || fx > 1 || fy < 0 || fy > 1) {
      document.getElementById('out').textContent = '点击点在数据范围外';
      return;
    }

    var col = Math.min(N - 1, Math.floor(fx * N));
    var row = Math.min(N - 1, Math.floor(fy * N));

    /* 只对当前可见的图层返回结果,与画面保持一致 */
    var parts = Object.keys(metrics).filter(function (k) {
      return layers[k].getVisible();
    }).map(function (k) {
      var m = metrics[k];
      return m.label + ' ' + m.value(row, col) + ' ' + m.unit;
    });

    document.getElementById('out').textContent =
      (row + ',' + col) + ' → ' + (parts.length ? parts.join(' · ') : '三层均已关闭');
  });

  document.getElementById('cb-pop').addEventListener('change', function () { layers.pop.setVisible(this.checked); });
  document.getElementById('cb-green').addEventListener('change', function () { layers.green.setVisible(this.checked); });
  document.getElementById('cb-temp').addEventListener('change', function () { layers.temp.setVisible(this.checked); });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLEGetfeatureinfo Tile OpenLayers · EXAMPLEGoogle OpenLayers · EXAMPLEGpx