forked from faroscore/leaflet-geotiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleaflet-geotiff.js
441 lines (386 loc) · 16.7 KB
/
leaflet-geotiff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// Ideas from:
// https://github.com/ScanEx/Leaflet.imageTransform/blob/master/src/L.ImageTransform.js
// https://github.com/BenjaminVadant/leaflet-ugeojson
// Depends on:
// https://github.com/constantinius/geotiff.js
// Note this will only work with ESPG:4326 tiffs
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
var L = require('leaflet');
var GeoTIFF = require('geotiff');
}
(function () {
try {
new window.ImageData(new Uint8ClampedArray([0, 0, 0, 0]), 1, 1);
} catch (e) {
var ImageDataPolyfill = function ImageDataPolyfill() {
var args = [].concat(Array.prototype.slice.call(arguments)),
data = void 0;
if (args.length < 2) {
throw new TypeError('Failed to construct "ImageData": 2 arguments required, but only ' + args.length + ' present.');
}
if (args.length > 2) {
data = args.shift();
if (!(data instanceof Uint8ClampedArray)) {
throw new TypeError('Failed to construct "ImageData": parameter 1 is not of type "Uint8ClampedArray"');
}
if (data.length !== 4 * args[0] * args[1]) {
throw new Error('Failed to construct "ImageData": The input data byte length is not a multiple of (4 * width * height)');
}
}
var width = args[0],
height = args[1],
canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
imageData = ctx.createImageData(width, height);
if (data) imageData.data.set(data);
return imageData;
};
window.ImageData = ImageDataPolyfill;
}
})();
L.LeafletGeotiff = L.ImageOverlay.extend({
options: {
arrowSize: 20,
band: 0,
image: 0,
renderer: null
},
initialize: function (url, options) {
if(typeof(GeoTIFF) === 'undefined'){
throw new Error("GeoTIFF not defined");
};
this._url = url;
this.raster = {};
L.Util.setOptions(this, options);
if (this.options.bounds) {
this._rasterBounds = L.latLngBounds(options.bounds);
}
if (this.options.renderer) {
this.options.renderer.setParent(this);
}
this._getData();
},
setURL: function(newURL) {
this._url = newURL;
this._getData();
},
onAdd: function (map) {
this._map = map;
if (!this._image) {
this._initImage();
if (this.options.interactive) {
L.DomUtil.addClass(this._image, 'leaflet-interactive');
this.addInteractiveTarget(this._image);
}
}
map._panes.overlayPane.appendChild(this._image);
map.on('moveend', this._reset, this);
if (map.options.zoomAnimation && L.Browser.any3d) {
map.on('zoomanim', this._animateZoom, this);
}
this._reset();
},
onRemove: function (map) {
map.getPanes().overlayPane.removeChild(this._image);
map.off('moveend', this._reset, this);
if (map.options.zoomAnimation) {
map.off('zoomanim', this._animateZoom, this);
}
},
_getData: function() {
var self = this;
var request = new XMLHttpRequest();
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
self._parseTIFF(this.response);
} //TODO else handle error
};
request.open("GET", this._url, true);
request.responseType = "arraybuffer";
request.send();
},
_parseTIFF: function (arrayBuffer) {
var self = this;
GeoTIFF.fromArrayBuffer(arrayBuffer).then(function(tiff){
self.tiff = tiff;
self.setBand(self.options.band);
if (!self.options.bounds) {
self.tiff.getImage(self.options.image).then(function(img){
var image = img;
var meta = image.getFileDirectory();
var x_min = meta.ModelTiepoint[3];
var x_max = x_min + meta.ModelPixelScale[0]*meta.ImageWidth;
var y_min = meta.ModelTiepoint[4];
var y_max = y_min - meta.ModelPixelScale[1]*meta.ImageLength;
self._rasterBounds = L.latLngBounds([[y_min,x_min],[y_max,x_max]]);
self._reset();
});
}
}).catch(function () {
var blob = new Blob([arrayBuffer], {type: 'image/png'});
var urlCreator = window.URL || window.webkitURL;
var src = urlCreator.createObjectURL(blob);
var img = new Image();
img.onload = function() {
var width = img.naturalWidth;
var height = img.naturalHeight;
const cnv = document.createElement('canvas');
const cnvCtx = cnv.getContext("2d");
cnv.width = width;
cnv.height = height;
cnvCtx.drawImage(img, 0, 0);
var imgData = cnvCtx.getImageData(0, 0, width, height);
var data = imgData.data;
var r = [];
var g = [];
var b = [];
var a = [];
data.forEach(function(color, i) {
var del = i % 4;
if (del === 0) r.push(color);
if (del === 1) g.push(color);
if (del === 2) b.push(color);
if (del === 3) a.push(color);
});
self.raster.data = [r, g, b, a].filter(function (v) {
return v;
});
self.raster.width = width;
self.raster.height = height;
self._rasterBounds = L.latLngBounds(self.options.imgBounds);
self._reset();
};
img.src = src;
});
},
setBand: function (band) {
var self = this;
self.options.band = band;
self.tiff.getImage(self.options.image).then(function(img){
var image = img;
image.readRasters({samples: self.options.samples}).then(function(data){
var r = data['0'];
var g = data['1'];
var b = data['2'];
var a = data['3'];
self.raster.data = [r,g,b,a].filter(function (v) {
return v;
});
self.raster.width = data.width;
self.raster.height = data.height;
self._reset()
});
});
},
getRasterArray: function () {
return this.raster.data;
},
getRasterCols: function () {
return this.raster.width;
},
getRasterRows: function () {
return this.raster.height;
},
getValueAtLatLng: function (lat, lng) {
try {
var lngSpan = (this._rasterBounds._northEast.lng - this._rasterBounds._southWest.lng) / this.raster.width;
var latSpan = (this._rasterBounds._northEast.lat - this._rasterBounds._southWest.lat) / this.raster.height;
var topLeft = this._rasterBounds.getNorthWest();
var x = Math.ceil((lng - topLeft.lng) / lngSpan);
var y = Math.ceil((topLeft.lat - lat) / latSpan);
if (x < 0 || y < 0 || x > this.raster.width || y > this.raster.height) {
return undefined;
}
var i = y * this.raster.width + x;
return this.raster.data[0][i];
}
catch(err) {
return undefined;
}
},
_animateZoom: function (e) {
if (L.version >= "1.0") {
var scale = this._map.getZoomScale(e.zoom),
offset = this._map._latLngBoundsToNewLayerBounds(this._map.getBounds(), e.zoom, e.center).min;
L.DomUtil.setTransform(this._image, offset, scale);
} else {
var scale = this._map.getZoomScale(e.zoom),
nw = this._map.getBounds().getNorthWest(),
se = this._map.getBounds().getSouthEast(),
topLeft = this._map._latLngToNewLayerPoint(nw, e.zoom, e.center),
size = this._map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft);
this._image.style[L.DomUtil.TRANSFORM] =
L.DomUtil.getTranslateString(topLeft) + ' scale(' + scale + ') ';
}
},
_reset: function () {
if (this.hasOwnProperty('_map') && this._map) {
if (this._rasterBounds) {
var topLeft = this._map.latLngToLayerPoint(this._map.getBounds().getNorthWest()),
size = this._map.latLngToLayerPoint(this._map.getBounds().getSouthEast())._subtract(topLeft);
L.DomUtil.setPosition(this._image, topLeft);
this._image.style.width = size.x + 'px';
this._image.style.height = size.y + 'px';
this._drawImage();
}
}
},
setClip: function(clipLatLngs) {
this.options.clip = clipLatLngs;
this._reset();
},
_getPixelByLatLng: function(latLng) {
var topLeft = this._map.latLngToLayerPoint(this._map.getBounds().getNorthWest());
var mercPoint = this._map.latLngToLayerPoint(latLng);
return L.point(mercPoint.x - topLeft.x, mercPoint.y - topLeft.y);
},
_clipMaskToPixelPoints: function(i) {
if (this.options.clip) {
var topLeft = this._map.latLngToLayerPoint(this._map.getBounds().getNorthWest());
var pixelClipPoints = [];
const clip = this.options.clip[i];
for (var p = 0; p < clip.length; p++) {
var mercPoint = this._map.latLngToLayerPoint(clip[p]),
pixel = L.point(mercPoint.x - topLeft.x, mercPoint.y - topLeft.y);
pixelClipPoints.push(pixel);
}
this._pixelClipPoints = pixelClipPoints;
} else {
this._pixelClipPoints = undefined;
}
},
_drawImage: function () {
if (this.raster.hasOwnProperty('data')) {
var args = {},
topLeft = this._map.latLngToLayerPoint(this._map.getBounds().getNorthWest()),
size = this._map.latLngToLayerPoint(this._map.getBounds().getSouthEast())._subtract(topLeft);
args.rasterPixelBounds = L.bounds(this._map.latLngToContainerPoint(this._rasterBounds.getNorthWest()),this._map.latLngToContainerPoint(this._rasterBounds.getSouthEast()));
args.xStart = (args.rasterPixelBounds.min.x>0 ? args.rasterPixelBounds.min.x : 0);
args.xFinish = (args.rasterPixelBounds.max.x<size.x ? args.rasterPixelBounds.max.x : size.x);
args.yStart = (args.rasterPixelBounds.min.y>0 ? args.rasterPixelBounds.min.y : 0);
args.yFinish = (args.rasterPixelBounds.max.y<size.y ? args.rasterPixelBounds.max.y : size.y);
args.plotWidth = args.xFinish-args.xStart;
args.plotHeight = args.yFinish-args.yStart;
if ((args.plotWidth<=0) || (args.plotHeight<=0)) {
var plotCanvas = document.createElement("canvas");
plotCanvas.width = size.x;
plotCanvas.height = size.y;
var ctx = plotCanvas.getContext("2d");
ctx.clearRect(0, 0, plotCanvas.width, plotCanvas.height);
this._image.src = plotCanvas.toDataURL();
return;
}
args.xOrigin = this._map.getPixelBounds().min.x+args.xStart;
args.yOrigin = this._map.getPixelBounds().min.y+args.yStart;
args.lngSpan = (this._rasterBounds._northEast.lng - this._rasterBounds._southWest.lng)/this.raster.width;
args.latSpan = (this._rasterBounds._northEast.lat - this._rasterBounds._southWest.lat)/this.raster.height;
//Draw image data to canvas and pass to image element
var plotCanvas = document.createElement("canvas");
plotCanvas.width = size.x;
plotCanvas.height = size.y;
var ctx = plotCanvas.getContext("2d");
ctx.clearRect(0, 0, plotCanvas.width, plotCanvas.height);
this.options.renderer.render(this.raster, plotCanvas, ctx, args);
var mask = this.createMask(size, args);
ctx.globalCompositeOperation = 'destination-out';
ctx.drawImage(mask, 0, 0);
if (typeof this.options.onImageReady === 'function') {
this.options.onImageReady(ctx.getImageData(0,0, size.x, size.y));
}
this._image.src = String(plotCanvas.toDataURL());
}
},
createSubmask: function(size, args, clip) {
var canvas = document.createElement("canvas");
canvas.width = size.x;
canvas.height = size.y;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < clip.length; i++) {
var ring = clip[i];
if (i > 0) { //inner ring
ctx.globalCompositeOperation = 'destination-out';
}
ctx.beginPath();
for (var j = 0; j < ring.length; j++) {
var pix = this._getPixelByLatLng(ring[j]);
ctx.lineTo(pix.x, pix.y);
}
ctx.fill();
}
return canvas;
},
createMask: function(size, args) {
var canvas = document.createElement("canvas");
canvas.width = size.x;
canvas.height = size.y;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(args.xStart, args.yStart, args.plotWidth, args.plotHeight);
//Draw clipping polygon
const clip = this.options.clip;
if (clip) {
ctx.globalCompositeOperation = 'destination-out';
for (var idx = 0; idx < clip.length; idx++) {
var submask = this.createSubmask(size, args, clip[idx])
ctx.drawImage(submask, 0, 0);
}
}
return canvas;
},
transform: function(rasterImageData, args) {
//Create image data and Uint32 views of data to speed up copying
var imageData = new ImageData(args.plotWidth, args.plotHeight);
var outData = imageData.data;
var outPixelsU32 = new Uint32Array(outData.buffer);
var inData = rasterImageData.data;
var inPixelsU32 = new Uint32Array(inData.buffer);
var zoom = this._map.getZoom();
var scale = this._map.options.crs.scale(zoom);
var d = 57.29577951308232; //L.LatLng.RAD_TO_DEG;
var transformationA = this._map.options.crs.transformation._a;
var transformationB = this._map.options.crs.transformation._b;
var transformationC = this._map.options.crs.transformation._c;
var transformationD = this._map.options.crs.transformation._d;
if (L.version >= "1.0") {
transformationA = transformationA*this._map.options.crs.projection.R;
transformationC = transformationC*this._map.options.crs.projection.R;
}
for (var y=0;y<args.plotHeight;y++) {
var yUntransformed = ((args.yOrigin+y) / scale - transformationD) / transformationC;
var currentLat = (2 * Math.atan(Math.exp(yUntransformed)) - (Math.PI / 2)) * d;
var rasterY = this.raster.height-Math.ceil((currentLat - this._rasterBounds._southWest.lat)/args.latSpan);
for (var x=0;x<args.plotWidth;x++) {
//Location to draw to
var index = (y*args.plotWidth+x);
//Calculate lat-lng of (x,y)
//This code is based on leaflet code, unpacked to run as fast as possible
//Used to deal with TIF being EPSG:4326 (lat,lon) and map being EPSG:3857 (m E,m N)
var xUntransformed = ((args.xOrigin+x) / scale - transformationB) / transformationA;
var currentLng = xUntransformed * d;
var rasterX = Math.floor((currentLng - this._rasterBounds._southWest.lng)/args.lngSpan);
var rasterIndex = (rasterY*this.raster.width+rasterX);
//Copy pixel value
outPixelsU32[index] = inPixelsU32[rasterIndex];
}
}
return imageData;
}
});
L.LeafletGeotiffRenderer = L.Class.extend({
initialize: function(options) {
L.setOptions(this, options);
},
setParent: function(parent) {
this.parent = parent;
},
render: function(raster, canvas, ctx, args) {
throw new Error('Abstract class');
}
});
L.leafletGeotiff = function (url, options) {
return new L.LeafletGeotiff(url, options);
};
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
module.exports = L;
}