You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Leaflet.js中使用GeoTIFF:点击地图获取像素值失败求助

解决GeoRasterLayer地图点击获取像素值的问题

你当前代码的核心问题是:Leaflet的地图点击事件对象e并没有自带pixelValue属性,直接访问e.pixelValue会拿到undefined,自然无法弹出数值。要实现点击获取像素值,需要利用GeoRaster提供的坐标转换方法,将点击的经纬度转换为影像内部的像素坐标,再读取对应位置的数值。

修改步骤:

  • 保留georaster实例的引用,确保在点击事件中可以访问到它
  • 使用georaster.latLngToPixel()方法,将点击的经纬度(e.latlng)转换为影像的像素行列坐标
  • 检查转换后的坐标是否在影像的有效范围内,避免点击到影像外时报错
  • 从georaster.values数组中取出对应位置的像素值(values[0]对应第一个波段)

修改后的完整代码:

var map = L.map('map').setView([12.46876, 121.915039], 6);

var layer = "http://{s}.basemaps.cartocdn.com/rastertiles/voyager_labels_under/{z}/{x}/{y}.png";
L.tileLayer(layer, {
  attribution: "OSM & Carto",
  subdomains: "abcd",
  maxZoom: 19
}).addTo(map);

// tif file
var url_to_geotiff_file = "../src/rr.gpm1hr.20221026.233000.tif";

fetch(url_to_geotiff_file)
  .then(response => response.arrayBuffer())
  .then(arrayBuffer => {
    parseGeoraster(arrayBuffer).then(georaster => {
      const min = georaster.mins[0];
      const max = georaster.maxs[0];
      const range = georaster.ranges[0];

      var scale = chroma.scale(['#FFFFCC' ,'#C7E9B4' ,'#7FCDBB' ,'#41B6C4' ,'#1D91C0' ,'#225EA8' ,'#0C2C84']);

      var layer = new GeoRasterLayer({
          georaster: georaster,
          opacity: 0.7,
          pixelValuesToColorFn: function(pixelValues) {
            var pixelValue = pixelValues[0];

            if (pixelValue === 0) return null;

            var scaledPixelValue = (pixelValue - min) / range;

            var color = scale(scaledPixelValue).hex();

            return color;
          },
          resolution: 256
      }).addTo(map);

      // 修改点击事件逻辑
      map.on('click', function (e) {
          // 将经纬度转换为影像像素坐标
          const [x, y] = georaster.latLngToPixel(e.latlng);
          
          // 检查坐标是否在影像有效范围内
          const isXValid = x >= 0 && x < georaster.width;
          const isYValid = y >= 0 && y < georaster.height;

          if (isXValid && isYValid) {
              const pixelValue = georaster.values[0][y][x];
              // 和渲染逻辑一致,忽略0值
              if (pixelValue !== 0) {
                  let html = (`<span class="popupText">Value: ${pixelValue}</span>`);
                  let popup = L.popup()
                      .setLatLng(e.latlng)
                      .setContent(html)
                      .openOn(map);
              }
          }
      });
    });
  });

关键说明:

  • georaster.latLngToPixel()返回的是[列号, 行号],所以读取值的时候要用values[波段][行号][列号]
  • 增加了坐标有效性检查,防止点击到影像范围外时出现数组越界错误
  • 保持了和你原有渲染逻辑一致的0值过滤规则

内容的提问来源于stack exchange,提问作者ChaM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 15:05:26