29#include <nlohmann/json.hpp>
47 mRootTileMatrix = tileMatrix;
58 mErrorMessage = tr(
"Invalid min. zoom level" );
63 mErrorMessage = tr(
"Invalid max. zoom level" );
67 std::unique_ptr<QgsMbTiles> mbtiles;
72 QString sourceType = dsUri.
param( QStringLiteral(
"type" ) );
73 QString sourcePath = dsUri.
param( QStringLiteral(
"url" ) );
74 if ( sourceType == QLatin1String(
"xyz" ) )
77 sourcePath = QUrl( sourcePath ).toLocalFile();
81 mErrorMessage = tr(
"Invalid template for XYZ: " ) + sourcePath;
85 else if ( sourceType == QLatin1String(
"mbtiles" ) )
91 mErrorMessage = tr(
"Unsupported source type for writing: " ) + sourceType;
101 mErrorMessage = tr(
"Failed to calculate output extent" );
107 int tilesToCreate = 0;
108 for (
int zoomLevel = mMinZoom; zoomLevel <= mMaxZoom; ++zoomLevel )
113 tilesToCreate += ( tileRange.
endRow() - tileRange.
startRow() + 1 ) *
117 if ( tilesToCreate == 0 )
119 mErrorMessage = tr(
"No tiles to generate" );
125 if ( !mbtiles->create() )
127 mErrorMessage = tr(
"Failed to create MBTiles file: " ) + sourcePath;
132 mbtiles->setMetadataValue(
"format",
"pbf" );
133 mbtiles->setMetadataValue(
"json", mbtilesJsonSchema() );
136 const QStringList metaKeys = mMetadata.keys();
137 for (
const QString &key : metaKeys )
139 mbtiles->setMetadataValue( key, mMetadata[key].toString() );
143 if ( !mMetadata.contains(
"name" ) )
144 mbtiles->setMetadataValue(
"name",
"unnamed" );
145 if ( !mMetadata.contains(
"minzoom" ) )
146 mbtiles->setMetadataValue(
"minzoom", QString::number( mMinZoom ) );
147 if ( !mMetadata.contains(
"maxzoom" ) )
148 mbtiles->setMetadataValue(
"maxzoom", QString::number( mMaxZoom ) );
149 if ( !mMetadata.contains(
"bounds" ) )
156 QString boundsStr = QString(
"%1,%2,%3,%4" )
159 mbtiles->setMetadataValue(
"bounds", boundsStr );
166 if ( !mMetadata.contains(
"crs" ) )
167 mbtiles->setMetadataValue(
"crs", mRootTileMatrix.
crs().
authid() );
170 int tilesCreated = 0;
171 for (
int zoomLevel = mMinZoom; zoomLevel <= mMaxZoom; ++zoomLevel )
176 for (
int row = tileRange.
startRow(); row <= tileRange.
endRow(); ++row )
184 for (
const Layer &layer : std::as_const( mLayers ) )
186 if ( ( layer.minZoom() >= 0 && zoomLevel < layer.minZoom() ) ||
187 ( layer.maxZoom() >= 0 && zoomLevel > layer.maxZoom() ) )
190 encoder.
addLayer( layer.layer(), feedback, layer.filterExpression(), layer.layerName() );
195 mErrorMessage = tr(
"Operation has been canceled" );
199 QByteArray tileData = encoder.
encode();
204 feedback->
setProgress(
static_cast<double>( tilesCreated ) / tilesToCreate * 100 );
207 if ( tileData.isEmpty() )
213 if ( sourceType == QLatin1String(
"xyz" ) )
215 if ( !writeTileFileXYZ( sourcePath, tileID, tileMatrix, tileData ) )
220 QByteArray gzipTileData;
222 int rowTMS = pow( 2, tileID.
zoomLevel() ) - tileID.
row() - 1;
223 mbtiles->setTileData( tileID.
zoomLevel(), tileID.
column(), rowTMS, gzipTileData );
236 for (
const Layer &layer : mLayers )
248 QgsDebugError(
"Failed to reproject layer extent to destination CRS" );
254bool QgsVectorTileWriter::writeTileFileXYZ(
const QString &sourcePath,
QgsTileXYZ tileID,
const QgsTileMatrix &tileMatrix,
const QByteArray &tileData )
259 QFileInfo fi( filePath );
260 QDir fileDir = fi.dir();
261 if ( !fileDir.exists() )
263 if ( !fileDir.mkpath(
"." ) )
265 mErrorMessage = tr(
"Cannot create directory " ) + fileDir.path();
271 if ( !f.open( QIODevice::WriteOnly ) )
273 mErrorMessage = tr(
"Cannot open file for writing " ) + filePath;
283QString QgsVectorTileWriter::mbtilesJsonSchema()
285 QVariantList arrayLayers;
286 for (
const Layer &layer : std::as_const( mLayers ) )
291 QVariantMap fieldsObj;
292 for (
const QgsField &field : fields )
294 QString fieldTypeStr;
295 if ( field.type() == QMetaType::Type::Bool )
296 fieldTypeStr = QStringLiteral(
"Boolean" );
297 else if ( field.type() == QMetaType::Type::Int || field.type() == QMetaType::Type::Double )
298 fieldTypeStr = QStringLiteral(
"Number" );
300 fieldTypeStr = QStringLiteral(
"String" );
302 fieldsObj[field.name()] = fieldTypeStr;
305 QVariantMap layerObj;
306 layerObj[
"id"] = vl->
name();
307 layerObj[
"fields"] = fieldsObj;
308 arrayLayers.append( layerObj );
312 rootObj[
"vector_layers"] = arrayLayers;
328 if ( ( layer.minZoom() >= 0 && zoomLevel < layer.minZoom() ) ||
329 ( layer.maxZoom() >= 0 && zoomLevel > layer.maxZoom() ) )
332 encoder.
addLayer( layer.layer(), feedback, layer.filterExpression(), layer.layerName() );
This class represents a coordinate reference system (CRS).
Custom exception class for Coordinate Reference System related exceptions.
Class for storing the component parts of a RDBMS data source URI (e.g.
void setEncodedUri(const QByteArray &uri)
Sets the complete encoded uri.
QString param(const QString &key) const
Returns a generic parameter value corresponding to the specified key.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
bool isCanceled() const
Tells whether the operation has been canceled already.
void setProgress(double progress)
Sets the current progress for the feedback object.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
static json jsonFromVariant(const QVariant &v)
Converts a QVariant v to a json object.
QgsCoordinateReferenceSystem crs
Utility class for reading and writing MBTiles files (which are SQLite3 databases).
A rectangle specified with double values.
double xMinimum() const
Returns the x minimum value (left side of rectangle).
double yMinimum() const
Returns the y minimum value (bottom side of rectangle).
double xMaximum() const
Returns the x maximum value (right side of rectangle).
double yMaximum() const
Returns the y maximum value (top side of rectangle).
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
bool isEmpty() const
Returns true if the rectangle has no area.
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
QgsTileRange tileRangeFromExtent(const QgsRectangle &mExtent) const
Returns tile range that fully covers the given extent.
static QgsTileMatrix fromWebMercator(int zoomLevel)
Returns a tile matrix for the usual web mercator.
QgsCoordinateReferenceSystem crs() const
Returns the crs of the tile matrix.
bool isRootTileMatrix() const
Returns the root status of the tile matrix (zoom level == 0)
static QgsTileMatrix fromTileMatrix(int zoomLevel, const QgsTileMatrix &tileMatrix)
Returns a tile matrix based on another one.
Range of tiles in a tile matrix to be rendered.
int endColumn() const
Returns index of the last column in the range.
int endRow() const
Returns index of the last row in the range.
int startRow() const
Returns index of the first row in the range.
int startColumn() const
Returns index of the first column in the range.
Stores coordinates of a tile in a tile matrix set.
int zoomLevel() const
Returns tile's zoom level (Z)
int column() const
Returns tile's column index (X)
int row() const
Returns tile's row index (Y)
Represents a vector layer which manages a vector based data sets.
QgsRectangle extent() const FINAL
Returns the extent of the layer.
Handles conversion of vector features to Mapbox vector tiles encoding.
void addLayer(QgsVectorLayer *layer, QgsFeedback *feedback=nullptr, QString filterExpression=QString(), QString layerName=QString())
Fetches data from vector layer for the given tile, does reprojection and clipping.
void setTileBuffer(int buffer)
Sets size of the buffer zone around tile edges in integer tile coordinates.
void setResolution(int extent)
Sets the resolution of coordinates of geometries within the tile.
QByteArray encode() const
Encodes MVT using data stored previously with addLayer() calls.
void setTransformContext(const QgsCoordinateTransformContext &transformContext)
Sets coordinate transform context for transforms between layers and tile matrix CRS.
static bool checkXYZUrlTemplate(const QString &url)
Checks whether the URL template string is correct (contains {x}, {y} / {-y}, {z} placeholders)
static QString formatXYZUrlTemplate(const QString &url, QgsTileXYZ tile, const QgsTileMatrix &tileMatrix)
Returns formatted tile URL string replacing {x}, {y}, {z} placeholders (or {-y} instead of {y} for TM...
Configuration of a single input vector layer to be included in the output.
bool setRootTileMatrix(const QgsTileMatrix &tileMatrix)
Sets zoom level 0 tile matrix.
QgsRectangle fullExtent() const
Returns calculated extent that combines extent of all input layers.
QByteArray writeSingleTile(QgsTileXYZ tileID, QgsFeedback *feedback=nullptr, int buffer=256, int resolution=4096) const
Encodes single MVT tile.
bool writeTiles(QgsFeedback *feedback=nullptr)
Writes vector tiles according to the configuration.
CORE_EXPORT bool encodeGzip(const QByteArray &bytesIn, QByteArray &bytesOut)
Encodes gzip byte stream, returns true on success.
#define QgsDebugError(str)