Files
td_official/src/utils/geoTiffLoader.ts

68 lines
2.0 KiB
TypeScript
Raw Normal View History

import { fromUrl } from 'geotiff'; // 假设你用的是这个包
import { transform } from 'ol/proj';
import { fromLonLat } from 'ol/proj';
import ImageLayer from 'ol/layer/Image';
import Static from 'ol/source/ImageStatic';
import gcoord from 'gcoord';
export class GeoTiffLoader {
imageExtent: number[] = [];
imageLayer: ImageLayer<Static> | null = null;
tiffUrl: string;
constructor(tiffUrl: string) {
this.tiffUrl = tiffUrl;
}
async init() {
const tiff = await fromUrl(this.tiffUrl);
const image = await tiff.getImage();
const width = image.getWidth();
const height = image.getHeight();
const bbox = image.getBoundingBox(); // [minX, minY, maxX, maxY]
console.log('bbox', bbox);
const rasters = (await image.readRasters({ interleave: true })) as Uint8Array;
// 创建 Canvas
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d')!;
const imageData = ctx.createImageData(width, height);
// 设置 RGBA 数据
imageData.data.set(rasters);
ctx.putImageData(imageData, 0, 0);
// 转成 Data URL
const imageUrl = canvas.toDataURL();
// 坐标转换
const minLonLat = transform([bbox[0], bbox[1]], 'EPSG:32648', 'EPSG:4326');
const maxLonLat = transform([bbox[2], bbox[3]], 'EPSG:32648', 'EPSG:4326');
// 转为 GCJ02 坐标系
// 这里断言为[number, number, number]补0做三维坐标
const gcjMin = gcoord.transform([minLonLat[0], minLonLat[1], 0], gcoord.WGS84, gcoord.GCJ02);
const gcjMax = gcoord.transform([maxLonLat[0], maxLonLat[1], 0], gcoord.WGS84, gcoord.GCJ02);
// 再转为 EPSG:3857
const minXY = fromLonLat(gcjMin);
const maxXY = fromLonLat(gcjMax);
this.imageExtent = [...minXY, ...maxXY];
this.imageLayer = new ImageLayer({
source: new Static({
url: imageUrl,
imageExtent: this.imageExtent,
projection: 'EPSG:3857'
})
});
console.log('imageExtent', this.imageExtent);
}
}