我已经尝试使用标准html中的leaflet.canvaslayer.field.js插件来显示一些GeoTiff,现在我想获得一些帮助,以了解如何将代码移植到react组件中。
我的JavaScript代码是:
d3.request('http://localhost:4000/map_tif/?band=223').responseType('arraybuffer').get(
function(error, tiffData) {
console.log(tiffData.response);
let ndvi = L.ScalarField.fromGeoTIFF(tiffData.response);
ndvi.isContinuous = false
ndvi.longitudeNeedsToBeWrapped = false
console.log(ndvi)
let layer = L.canvasLayer.scalarField(ndvi, {
color: chroma.scale('Spectral').domain(ndvi.range.reverse()),
opacity: 1,
inFilter: (v) => v !== 0
}).addTo(map);
layer.on('click', function(e) {
if (e.value !== null) {
let v = e.value.toFixed(2);
let html = (`<span class = "popupText"> Temperature ${v} °C</span>`);
let popup = L.popup()
.setLatLng(e.latlng)
.setContent(html)
.openOn(map);
}
});
map.fitBounds(layer.getBounds());
});
谢谢
通常,您必须通过npm安装以下依赖项:
chroma.js
@ turf / insid
geotiff.js
d3js插件需要这些,然后将它们导入到您的组件中。
但是,正如所提到的here,此插件必须通过标签包含,并且不能通过标准的导入/请求语法轻松地导入到现代捆绑的JS应用程序中]
根据插件脚本的要求,通过index.html上的脚本标签导入前三个依赖项。index.html:
...
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://npmcdn.com/[email protected]/dist/geotiff.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/1.3.0/chroma.min.js"></script>
...
脚本标签由于某种原因在React项目中也不起作用,因此您可以异步加载脚本并在加载时访问它。
const mapRef = useRef();
useEffect(() => {
const map = mapRef.current.leafletElement;
const script = document.createElement("script");
script.src =
"https://ihcantabria.github.io/Leaflet.CanvasLayer.Field/dist/leaflet.canvaslayer.field.js";
script.async = true;
script.onload = () => loaded(map);
document.body.appendChild(script);
}, []);
const loaded = map => {
var tiff =
"https://ihcantabria.github.io/Leaflet.CanvasLayer.Field/data/tz850.tiff";
fetch(tiff)
.then(r => r.arrayBuffer())
.then(function(buffer) {
var s = L.ScalarField.fromGeoTIFF(buffer);
let layer = L.canvasLayer.scalarField(s).addTo(map);
layer.on("click", function(e) {
if (e.value !== null) {
L.popup()
.setLatLng(e.latlng)
.setContent(`${e.value}`)
.openOn(map);
}
});
map.fitBounds(layer.getBounds());
});
};