2
0

More than 1 year has passed since last update.

Denoでお試しMBTilesサーバーを書いた

Last updated at Posted at 2021-10-02

TL;DR

import { listenAndServe } from 'https://deno.land/std@0.109.0/http/server.ts';
import { DB } from 'https://deno.land/x/sqlite@v3.1.1/mod.ts';
import { expandGlob } from 'https://deno.land/std@0.109.0/fs/expand_glob.ts';
import { gunzip } from 'https://deno.land/x/compress@v0.4.1/mod.ts';

// make connections to .MBTiles files in './tiles'
const connections: { [key: string]: DB } = {};
for await (const mbtiles of expandGlob('tiles/*.mbtiles')) {
    connections[mbtiles.name.split('.')[0]] = new DB(mbtiles.path);
}

listenAndServe(':8000', (request) => {
    const [tilename, z, x, y] = request.url.split('/').slice(-4);
    const fy = Math.pow(2, Number(z)) - Number(y.split('.')[0]) - 1;

    if (typeof connections[tilename] === 'undefined') {
        return new Response('mbtiles is not exist', { status: 404 });
    }

    const pbf = connections[tilename].query(
        `select tile_data from tiles where zoom_level=${z} and tile_column=${x} and tile_row=${fy};`,
    );
    if (pbf.length === 0) {
        return new Response('tile is not exist', { status: 404 });
    }

    return new Response(gunzip(pbf[0][0] as Uint8Array));
});


  • 30行くらいしか書いてない
  • HTTPサーバーのAPIの変更が激しくてドキュメントがないっぽい
  • MapboxVectorTile形式にしか対応してない(画像には非対応)

使い方

  1. copy MBTIles files into tiles directory.
  2. launch server
deno run --allow-net --allow-read --allow-write server.ts
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0