mbtiles

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 6, 2023 License: BSD-2-Clause Imports: 6 Imported by: 1

README

go-mbtiles

PkgGoDev

Package mbtiles reads and writes files in the MBTiles format.

Running the http server

go install github.com/twpayne/go-mbtiles/cmd/mbtiles-server
go run github.com/twpayne/go-mbtiles/cmd/mbtiles-server -addr localhost:9091 -dsn ./testdata/openstreetmap.org.mbtiles

Reading mbtiles files

MBTiles files are SQLite databases, and opened using a DSN string.

Create a reader and read a tile with:

reader, err := mbtiles.NewReader("./testdata/openstreetmap.org.mbtiles")
if err != nil {
	panic(err)
}
tile, err := reader.SelectTile(0, 0, 0)
if err != nil {
	if errors.Is(err, sql.ErrNoRows) {
		fmt.Printf("tile doesn't exist: %d, %d, %d\n", 0, 0, 0)
		return
	} else {
		panic(err)
	}
}
fmt.Printf("tile data: %+v\n", tile)

Note that SQLite will happily open a non-existant file to read without throwing an error. It is recommend that you check for existance of the file first, if you're using a file path as your DSN. For example:

if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
	panic(fmt.Sprintf("mbtiles file doesn't exist (%s): %v", filename, err))
}

The Reader type includes a ServeHTTP function. You can use it to create a reader for your mbtiles.

Writing mbtiles files

This package supports writing files in the MBTiles v1.3 format.

The library will not fill out all the required fields in the MBTiles specification, instead it provides the tools to be compliant.

Of note:

  • The caller is responsible for populating the correct metadata into the metadata persuant to the spec.
  • The caller is responsible for gzip'ing the tile data before calling InsertTile or BulkInsertTile. The spec requires tiles to be compressed with gzip. How the caller implements the compression is outside the scope of this package.
  • For the json key in the metadata table, helper types are provided in this package as mbtiles.MetadataJson. This type can be marshaled to a string and inserted into the metadata table for spec compliance for vector MBTiles files.
  • go-mbtiles will invert the Y coordinate to TMS to be compliant with the mbtiles spec.
  • go-mbtiles will create a metadata table if it doesn't exist, the first time InsertMetadata is called.
  • go-mbtiles will create a tiles table if it doesn't exist, the first time InsertTile or BulkInsertTile is called.
Performance Tips

MBTiles files are SQLite databases. To performantly bulk insert a large number of rows into the database, certain optimizations may be necessary to improve write performance.

SQLite is a a single writer database, which means only one write can occur at a time. The database will otherwise be locked. Because of this, any write that is not in a transaction will automatically be wrapped in a transaction, which is slow. Consider the BulkInsertTile command, which will wrap all of the inserts in a single transaction.

There are other optimizations exposed through the Writer interface. You should understand their implications for your use case before turning them on.

  • JournalModeMemory switches journaling from disk to memory. In bulk import scenarios, this is likely a very safe performance optimization to turn on.
  • SynchronousOff allows SQLite to continue processing as soon as data is handed off to the operating system to be written (instead of wait for confirmation that the write was successful). This is likely safe for bulk writes, but likely will result in a corrupted database if the process is interrupted or computer loses power.

The performance improvements in go-mbtiles are motivated by the research in this StackOverflow post about SQLite INSERT performance.

License

BSD-2-Clause in LICENCE.

Contributors

  • Tom Payne (@twpayne)
  • Joe Polastre (@polastre), FlightAware

Documentation

Overview

Package mbtiles reads and writes files in the MBTiles format. See https://github.com/mapbox/mbtiles-spec.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MetadataJson

type MetadataJson struct {
	VectorLayers []MetadataJsonVectorLayer `json:"vector_layers"` // Defines the vector layers in this mbtiles file. Required for vector tilesets (mvt/pbf). Not necessary for raster image (png/webp/jpg/etc) mbtiles files.
}

MetadataJson is the metadata required by the mbtiles spec to be present for vector tiles in the metadata table. This struct should be marshaled to a UTF-8 string and the value stored with key name `json`.

See https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md#vector-tileset-metadata

type MetadataJsonVectorLayer

type MetadataJsonVectorLayer struct {
	ID          *string           `json:"id"`                    // The layer ID, which is referred to as the name of the layer in the Mapbox Vector Tile spec.
	Description *string           `json:"description,omitempty"` // A human-readable description of the layer's contents.
	MinZoom     *int              `json:"minzoom,omitempty"`     // The lowest zoom level whose tiles this layer appears in.
	MaxZoom     *int              `json:"maxzoom,omitempty"`     // The highest zoom level whose tiles this layer appears in.
	Fields      map[string]string `json:"fields"`                // Fields has keys and values are the names and types of attributes available in this layer. Each type MUST be the string "Number", "Boolean", or "String". Attributes whose type varies between features SHOULD be listed as "String".
}

MetadataJsonVectorLayer contains information about each vector tile layer in this mbtiles file.

type Optimizations

type Optimizations struct {
	// Synchronous turns ON or OFF the statement PRAGMA synchronous = OFF.
	SynchronousOff bool
	// JournalModeMemory turns ON or OFF the statement PRAGMA journal_mode = MEMORY.
	JournalModeMemory bool
}

Optimizations are options that can be turned on/off for writing mbtiles files, however they do have side-effects so best to research before using them.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

A Reader reads a tileset.

func NewReader

func NewReader(dsn string) (*Reader, error)

NewReader returns a new Reader.

func NewReaderWithDB

func NewReaderWithDB(db *sql.DB) (*Reader, error)

NewReaderWithDB returns a new Reader initialized with a sql.Database. This is useful for instantiating alternative implementations of sqlite.

func (*Reader) Close

func (r *Reader) Close() error

Close releases all resources associated with r.

func (*Reader) SelectMetadata

func (r *Reader) SelectMetadata(name string) (string, error)

SelectMetadata returns the metadata value for 'name'

func (*Reader) SelectTile

func (r *Reader) SelectTile(z, x, y int) ([]byte, error)

SelectTile returns the tile at (z, x, y).

func (*Reader) ServeHTTP

func (r *Reader) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements http.Handler.

type TileData

type TileData struct {
	X    int    // X coordinate in ZXY format
	Y    int    // Y coordinate in ZXY format
	Z    int    // Z coordinate in ZXY format
	Data []byte // Tile data, must be gzip encoded for mbtiles
}

TileData represents a single tile for writing to the mbtiles file.

type Writer

type Writer struct {
	Reader
	// contains filtered or unexported fields
}

A Writer writes a tileset. It should be created with NewWriter().

func NewWriter

func NewWriter(dsn string) (*Writer, error)

NewWriter returns a new Writer.

func NewWriterWithDB

func NewWriterWithDB(db *sql.DB) (*Writer, error)

NewWriterWithDB returns a new Writer initialized with a sql.Database. This is useful for instantiating alternative implementations of sqlite.

func (*Writer) BulkInsertTile

func (w *Writer) BulkInsertTile(data []TileData) error

BulkInsertTile inserts multiple tiles at the coordinates provided (z, x, y). This can be faster because it reduces the number of transactions. By default, sqlite wraps each insert in a transaction.

func (*Writer) Close

func (w *Writer) Close() error

Close releases all resources with w.

func (*Writer) CreateMetadata

func (w *Writer) CreateMetadata() error

CreateMetadata creates the metadata table if it does not already exist.

func (*Writer) CreateTileIndex

func (w *Writer) CreateTileIndex() error

CreateTileIndex generates the standard index on the tiles table.

func (*Writer) CreateTiles

func (w *Writer) CreateTiles() error

CreateTiles creates the tiles table if it does not already exist.

func (*Writer) DeleteMetadata

func (w *Writer) DeleteMetadata() error

DeleteMetadata removes the metadata table, useful for resetting the metadata in the mbtiles file.

func (*Writer) DeleteTileIndex

func (w *Writer) DeleteTileIndex() error

DeleteTileIndex removes the tile index, useful for speeding up bulk inserts.

func (*Writer) InsertMetadata

func (w *Writer) InsertMetadata(name string, value string) error

InsertMetadata inserts a name, value row to the metadata store.

func (*Writer) InsertTile

func (w *Writer) InsertTile(z, x, y int, tileData []byte) error

InsertTile inserts a tile at (z, x, y).

func (*Writer) SelectMetadata

func (w *Writer) SelectMetadata(name string) (string, error)

SelectMetadata returns the metadata value for name.

func (*Writer) SelectTile

func (w *Writer) SelectTile(z, x, y int) ([]byte, error)

SelectTile returns the tile at (z, x, y).

func (*Writer) SetOptimizations

func (w *Writer) SetOptimizations(opts Optimizations) error

SetOptimizations can be used to turn on or off Optimization options.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL