Last active
December 12, 2022 20:07
-
-
Save jukben/a8170c4fdfa85806310bee60bb4a384c to your computer and use it in GitHub Desktop.
Custom Layer for react-leafleat with naive cache mechanism
This file contains 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
import { withLeaflet, GridLayer } from "react-leaflet"; | |
import L from "leaflet"; | |
class Grid extends GridLayer { | |
createLeafletElement() { | |
const { url, cacheName } = this.props; | |
const Layer = L.TileLayer.extend({ | |
createTile: (coords, done) => { | |
const { x, y, z } = coords; | |
// this is the url for tile | |
const tileUrl = url | |
.replace("{x}", x) | |
.replace("{y}", y) | |
.replace("{z}", z); | |
// create new instance of Image (later filled with cached data blob) | |
const tileImage = new Image(); | |
// use the actual url as fallback in case we didn't cached it | |
tileImage.src = tileUrl; | |
try { | |
caches.open(cacheName).then(cache => { | |
cache.match(tileUrl).then(tile => { | |
// in the case we haven't found a cached tile let's return fallback | |
if (!tile) { | |
done(); | |
return; | |
} | |
// we have something, let's transform the blob and render it! | |
tile.blob().then(blob => { | |
const tileImageData = URL.createObjectURL(blob); | |
tileImage.src = tileImageData; | |
done(); | |
}); | |
}); | |
}); | |
} catch (e) { | |
console.warn("CachedLayer issue", e); | |
done(); | |
} | |
return tileImage; | |
} | |
}); | |
return new Layer(url); | |
} | |
} | |
export default withLeaflet(Grid); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment