Load tiles with base64 encoding

The example of load tile images by BASE64 encoding, a very common way to load offline tiles in mobiles.

You can save tile images in sqlite database, and load them as following:

  • Override TileLayer's getTileUrl method, return sqlite url with given x,y,z
  • Override TileLayer renderer's getTileImage method, fetch image base64 from sqlite, and set it to Image.src

Recommend mbtiles, a great spec to store tiles in sqlite database.

<!DOCTYPE html>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>TileLayer and Geo-Projections - Load tiles with base64 encoding</title>
  <style type="text/css">
  <link rel="stylesheet" href="https://unpkg.com/maptalks/dist/maptalks.css">
  <script type="text/javascript" src="https://unpkg.com/maptalks/dist/maptalks.min.js"></script>
    <div id="map" class="container"></div>

      var baseLayer = new maptalks.TileLayer('base',{
        urlTemplate: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
        subdomains: ["a","b","c","d"],
        attribution: '&copy; <a href="http://osm.org">OpenStreetMap</a> contributors, &copy; <a href="https://carto.com/">CARTO</a>'

      //generate tile url
      baseLayer.getTileUrl = function (x, y, z) {
        //replace with your own
        //e.g. return a url pointing to your sqlite database
        return maptalks.TileLayer.prototype.getTileUrl.call(this, x, y, z);

      baseLayer.on('renderercreate', function (e) {
        //load tile image
        //   img(Image): an Image object
        //   url(String): the url of the tile
        e.renderer.loadTileImage = function (img, url) {
          //mocking getting image's base64
          //replace it by your own, e.g. load from sqlite database
          var remoteImage = new Image();
          remoteImage.crossOrigin = 'anonymous';
          remoteImage.onload = function () {
            var base64 = getBase64Image(remoteImage);
            img.src = base64;
          remoteImage.src = url;

      function getBase64Image(img) {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);

        var dataURL = canvas.toDataURL('image/png');
        return dataURL;

      var map = new maptalks.Map('map', {
        center:     [-0.113049,51.498568],
        zoom:  11,
        baseLayer : baseLayer