Created
November 19, 2020 07:13
-
-
Save rahulhaque/18ae4c06e1d501608c7319bf9a6eb88a to your computer and use it in GitHub Desktop.
Leaflet to support custom headers. Credit - https://github.com/ticinum-aerospace/leaflet-wms-header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
L.TileLayer(MAP_URL, { | |
attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a>', | |
}, [ | |
{header: 'Authorization', value: ACCESS_TOKEN} | |
], null).addTo(map); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
async function fetchImage(url, callback, headers, abort) { | |
let _headers = {}; | |
if (headers) { | |
headers.forEach(h => { | |
_headers[h.header] = h.value; | |
}); | |
} | |
const controller = new AbortController(); | |
const signal = controller.signal; | |
if (abort) { | |
abort.subscribe(() => { | |
controller.abort(); | |
}); | |
} | |
const f = await fetch(url, { | |
method: "GET", | |
headers: _headers, | |
mode: "cors", | |
signal: signal | |
}); | |
const blob = await f.blob(); | |
callback(blob); | |
} | |
L.TileLayerWithHeaders = L.TileLayer.extend({ | |
initialize: function (url, options, headers, abort) { | |
L.TileLayer.prototype.initialize.call(this, url, options); | |
this.headers = headers; | |
this.abort = abort; | |
}, | |
createTile(coords, done) { | |
const url = this.getTileUrl(coords); | |
const img = document.createElement("img"); | |
img.setAttribute("role", "presentation"); | |
fetchImage( | |
url, | |
resp => { | |
const reader = new FileReader(); | |
reader.onload = () => { | |
img.src = reader.result; | |
}; | |
reader.readAsDataURL(resp); | |
done(null, img); | |
}, | |
this.headers, | |
this.abort | |
); | |
return img; | |
} | |
}); | |
L.tileLayer = function (url, options, headers, abort) { | |
return new L.TileLayerWithHeaders(url, options, headers, abort); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment