用base64编码载入瓦片

瓦片BASE64编码载入的示例, 很适合用于移动端中加载离线地图瓦片.

预先将瓦片数据存入sqlite数据库, 然后按照示例中所示:

  • 重写TileLayer的getTileUrl方法, 根据x,y,z返回sqlite的连接字
  • 重写TileLayer renderer的getTileImage方法, 用sqlite连接字查询数据库, 返回base64后, 设置给image.src

瓦片存储有一种专门格式, mbtiles格式, 可以作为在移动端存储瓦片的参考格式

index.html
<!DOCTYPE html>
<html>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>瓦片图层与地理投影 - 用base64编码载入瓦片</title>
  <style type="text/css">
    html,body{margin:0px;height:100%;width:100%}
    .container{width:100%;height:100%}
  </style>
  <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>
  <body>
    <div id="map" class="container"></div>

    <script>
      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
      });



    </script>
  </body>
</html>
已复制!