NDVI 来自 a Sentinel 2 COG
NDVI 来自 a Sentinel 2 COG示例。 COG NDVI
本示例中的 GeoTIFF 图层使用两个 Sentinel 2 数据源:红色波段和近红外波段。图层样式中包含一个 color 表达式,用于根据这两个波段的值计算归一化植被指数(NDVI)。interpolate 表达式用于将 NDVI 值映射为颜色。可以使用 layer.getData() 方法从 GeoTIFF 中获取像素值。移动鼠标或在地图上点击,即可查看基于红色和近红外像素值计算出的 NDVI 值。
main.js
js
import Map from 'ol/Map.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import GeoTIFF from 'ol/source/GeoTIFF.js';
const source = new GeoTIFF({
sources: [
{
// 可见光红波段,即上方样式表达式中的第 1 波段
url: 'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/36/Q/WD/2020/7/S2A_36QWD_20200701_0_L2A/B04.tif',
max: 10000,
},
{
// 近红外波段,即上方样式表达式中的第 2 波段
url: 'https://sentinel-cogs.s3.us-west-2.amazonaws.com/sentinel-s2-l2a-cogs/36/Q/WD/2020/7/S2A_36QWD_20200701_0_L2A/B08.tif',
max: 10000,
},
],
});
const layer = new TileLayer({
style: {
color: [
'interpolate',
['linear'],
// 计算 NDVI,波段来自下面的数据源
['/', ['-', ['band', 2], ['band', 1]], ['+', ['band', 2], ['band', 1]]],
// NDVI 值的色带,范围从 -1 到 1
-0.2,
[191, 191, 191],
-0.1,
[219, 219, 219],
0,
[255, 255, 224],
0.025,
[255, 250, 204],
0.05,
[237, 232, 181],
0.075,
[222, 217, 156],
0.1,
[204, 199, 130],
0.125,
[189, 184, 107],
0.15,
[176, 194, 97],
0.175,
[163, 204, 89],
0.2,
[145, 191, 82],
0.25,
[128, 179, 71],
0.3,
[112, 163, 64],
0.35,
[97, 150, 54],
0.4,
[79, 138, 46],
0.45,
[64, 125, 36],
0.5,
[48, 110, 28],
0.55,
[33, 97, 18],
0.6,
[15, 84, 10],
0.65,
[0, 69, 0],
],
},
source: source,
});
const map = new Map({
target: 'map',
layers: [layer],
view: source.getView(),
});
const output = document.getElementById('output');
function displayPixelValue(event) {
const data = layer.getData(event.pixel);
if (!data) {
return;
}
const red = data[0];
const nir = data[1];
const ndvi = (nir - red) / (nir + red);
output.textContent = ndvi.toFixed(2);
}
map.on(['pointermove', 'click'], displayPixelValue);index.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>来自 Sentinel 2 COG 的 NDVI</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<div>NDVI: <span id="output"></span></div>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "cog-math",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}