21#include <QJsonDocument>
45 QgsVectorTileProviderConnection::Data data = QgsVectorTileProviderConnection::decodedUri( uri );
46 if ( forceUpdate || ( data.url.isEmpty() && !data.styleUrl.isEmpty() ) )
48 const QMap<QString, QString> sources = QgsVectorTileUtils::parseStyleSourceUrl( data.styleUrl, data.httpHeaders, data.authCfg );
49 QMap<QString, QString>::const_iterator it = sources.constBegin();
51 for ( ; it != sources.constEnd(); ++it )
54 QString urlKey = QStringLiteral(
"url" );
55 QString nameKey = QStringLiteral(
"urlName" );
58 urlKey.append( QString(
"_%1" ).arg( i ) );
59 nameKey.append( QString(
"_%1" ).arg( i ) );
61 uri.append( QString(
"&%1=%2" ).arg( nameKey, it.key() ) );
62 uri.append( QString(
"&%1=%2" ).arg( urlKey, it.value() ) );
67QMap<QString, QString> QgsVectorTileUtils::parseStyleSourceUrl(
const QString &styleUrl,
const QgsHttpHeaders &headers,
const QString &authCfg )
70 nr.setUrl( QUrl( styleUrl ) );
78 QgsDebugError( QStringLiteral(
"Request failed: " ) + styleUrl );
79 return QMap<QString, QString>();
84 const QJsonDocument doc = QJsonDocument::fromJson( reply.
content(), &err );
87 QgsDebugError( QStringLiteral(
"Could not load style: %1" ).arg( err.errorString() ) );
89 else if ( !doc.isObject() )
91 QgsDebugError( QStringLiteral(
"Could not read style, JSON object is expected" ) );
95 QMap<QString, QString> sources;
96 QJsonObject sourcesData = doc.object().value( QStringLiteral(
"sources" ) ).toObject();
97 if ( sourcesData.count() == 0 )
99 QgsDebugError( QStringLiteral(
"Could not read sources in the style" ) );
103 QJsonObject::const_iterator it = sourcesData.constBegin();
104 for ( ; it != sourcesData.constEnd(); ++it )
106 const QString sourceName = it.key();
107 const QJsonObject sourceData = it.value().toObject();
108 if ( sourceData.value( QStringLiteral(
"type" ) ).toString() != QLatin1String(
"vector" ) )
115 if ( sourceData.contains( QStringLiteral(
"tiles" ) ) )
117 tiles = sourceData[
"tiles"].toArray().toVariantList();
119 else if ( sourceData.contains( QStringLiteral(
"url" ) ) )
121 tiles = parseStyleSourceContentUrl( sourceData.value( QStringLiteral(
"url" ) ).toString(), headers, authCfg );
125 QgsDebugError( QStringLiteral(
"Could not read source %1" ).arg( sourceName ) );
127 if ( tiles.count() == 0 )
129 QgsDebugError( QStringLiteral(
"Could not read source %1, not tiles found" ).arg( sourceName ) );
135 sources.insert( sourceName, tiles[rand() % tiles.count()].toString() );
141 return QMap<QString, QString>();
144QVariantList QgsVectorTileUtils::parseStyleSourceContentUrl(
const QString &sourceUrl,
const QgsHttpHeaders &headers,
const QString &authCfg )
147 nr.setUrl( QUrl( sourceUrl ) );
155 QgsDebugError( QStringLiteral(
"Request failed: " ) + sourceUrl );
156 return QVariantList();
161 const QJsonDocument doc = QJsonDocument::fromJson( reply.
content(), &err );
164 QgsDebugError( QStringLiteral(
"Could not load style: %1" ).arg( err.errorString() ) );
166 else if ( !doc.isObject() )
168 QgsDebugError( QStringLiteral(
"Could not read style, JSON object is expected" ) );
172 return doc.object().value( QStringLiteral(
"tiles" ) ).toArray().toVariantList();
174 return QVariantList();
197 QStringList fieldsSorted = qgis::setToList( flds );
198 std::sort( fieldsSorted.begin(), fieldsSorted.end() );
199 for (
const QString &fieldName : std::as_const( fieldsSorted ) )
209 double tileZoom2 = log( s0 / mapScale ) / log( 2 );
216 int tileZoom =
static_cast<int>( round(
scaleToZoom( mapScale, z0Scale ) ) );
218 if ( tileZoom < sourceMinZoom )
219 tileZoom = sourceMinZoom;
220 if ( tileZoom > sourceMaxZoom )
221 tileZoom = sourceMaxZoom;
230 decoder.
decode( rawTile );
231 QSet<QString> fieldNames = qgis::listToSet( decoder.
layerFieldNames( layerName ) );
232 fieldNames << QStringLiteral(
"_geom_type" );
233 QMap<QString, QgsFields> perLayerFields;
235 perLayerFields[layerName] = fields;
240 for (
int i = 0; i < featuresList.count(); ++i )
247 for (
int k = 0; k < ggc->numGeometries(); ++k )
272 turl.replace( QLatin1String(
"{x}" ), QString::number( tile.
column() ), Qt::CaseInsensitive );
273 if ( turl.contains( QLatin1String(
"{-y}" ) ) )
275 turl.replace( QLatin1String(
"{-y}" ), QString::number( tileMatrix.
matrixHeight() - tile.
row() - 1 ), Qt::CaseInsensitive );
279 turl.replace( QLatin1String(
"{y}" ), QString::number( tile.
row() ), Qt::CaseInsensitive );
281 turl.replace( QLatin1String(
"{z}" ), QString::number( tile.
zoomLevel() ), Qt::CaseInsensitive );
287 return url.contains( QStringLiteral(
"{x}" ) ) &&
288 ( url.contains( QStringLiteral(
"{y}" ) ) || url.contains( QStringLiteral(
"{-y}" ) ) ) &&
289 url.contains( QStringLiteral(
"{z}" ) );
298 QPointF p1( req1.
column() + 0.5, req1.
row() + 0.5 );
299 QPointF p2( req2.
column() + 0.5, req2.
row() + 0.5 );
301 double d1 = std::max( std::fabs(
center.x() - p1.x() ), std::fabs(
center.y() - p1.y() ) );
302 double d2 = std::max( std::fabs(
center.x() - p2.x() ), std::fabs(
center.y() - p2.y() ) );
311 std::sort( tiles.begin(), tiles.end(), cmp );
316 if ( styleDefinition.contains( QStringLiteral(
"sprite" ) ) && ( context.
spriteDefinitions().empty() || context.
spriteImage().isNull() ) )
319 QString spriteUriBase;
320 if ( styleDefinition.value( QStringLiteral(
"sprite" ) ).toString().startsWith( QLatin1String(
"http" ) ) )
322 spriteUriBase = styleDefinition.value( QStringLiteral(
"sprite" ) ).toString();
326 spriteUriBase = styleUrl +
'/' + styleDefinition.value( QStringLiteral(
"sprite" ) ).toString();
329 for (
int resolution = 2; resolution > 0; resolution-- )
331 QUrl spriteUrl = QUrl( spriteUriBase );
332 spriteUrl.setPath( spriteUrl.path() + QStringLiteral(
"%1.json" ).arg( resolution > 1 ? QStringLiteral(
"@%1x" ).arg( resolution ) : QString() ) );
333 QNetworkRequest request = QNetworkRequest( spriteUrl );
336 switch ( networkRequest.
get( request ) )
344 QUrl spriteUrl = QUrl( spriteUriBase );
345 spriteUrl.setPath( spriteUrl.path() + QStringLiteral(
"%1.png" ).arg( resolution > 1 ? QStringLiteral(
"@%1x" ).arg( resolution ) : QString() ) );
346 QNetworkRequest request = QNetworkRequest( spriteUrl );
349 switch ( networkRequest.
get( request ) )
354 const QImage spriteImage( QImage::fromData( imageContent.
content() ) );
355 context.
setSprites( spriteImage, spriteDefinition );
Abstract base class for all geometries.
virtual QgsAbstractGeometry * clone() const =0
Clones the geometry by performing a deep copy.
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
void setAuthCfg(const QString &authCfg)
Sets the authentication config id which should be used during the request.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NetworkError
A network error occurred.
@ ServerExceptionError
An exception was raised by the server.
@ NoError
No error was encountered.
@ TimeoutError
Timeout was reached before a reply was received.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
QList< QgsField > toList() const
Utility function to return a list of QgsField instances.
virtual bool addGeometry(QgsAbstractGeometry *g)
Adds a geometry and takes ownership. Returns true in case of success.
A geometry is the spatial representation of a feature.
const QgsAbstractGeometry * constGet() const
Returns a non-modifiable (const) reference to the underlying abstract geometry primitive.
static QVariant parseJson(const std::string &jsonString)
Converts JSON jsonString to a QVariant, in case of parsing error an invalid QVariant is returned and ...
Context for a MapBox GL style conversion operation.
void setSprites(const QImage &image, const QVariantMap &definitions)
Sets the sprite image and definitions JSON to use during conversion.
QImage spriteImage() const
Returns the sprite image to use during conversion, or an invalid image if this is not set.
QVariantMap spriteDefinitions() const
Returns the sprite definitions to use during conversion.
Perform transforms between map coordinates and device coordinates.
QgsPointXY transform(const QgsPointXY &p) const
Transforms a point p from map (world) coordinates to device coordinates.
Encapsulates a network reply within a container which is inexpensive to copy and safe to pass between...
QByteArray content() const
Returns the reply content.
A class to represent a 2D point.
QPointF toQPointF() const
Converts a point to a QPointF.
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).
Defines a matrix of tiles for a single zoom level: it is defined by its size (width *.
QgsRectangle tileExtent(QgsTileXYZ id) const
Returns extent of the given tile in this matrix.
int matrixHeight() const
Returns number of rows of the tile matrix.
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)
bool addFeatures(QgsFeatureList &flist, QgsFeatureSink::Flags flags=QgsFeatureSink::Flags()) override
Adds a list of features to the sink.
virtual bool addAttributes(const QList< QgsField > &attributes)
Adds new attributes to the provider.
Represents a vector layer which manages a vector based data sets.
long long featureCount(const QString &legendKey) const
Number of features rendered with specified legend key.
void updateFields()
Will regenerate the fields property of this layer by obtaining all fields from the dataProvider,...
virtual void updateExtents(bool force=false)
Update the extents for the layer.
QgsVectorDataProvider * dataProvider() FINAL
Returns the layer's data provider, it may be nullptr.
Implements a map layer that is dedicated to rendering of vector tiles.
QgsVectorTileRawData getRawTile(QgsTileXYZ tileID)
Fetches raw tile data for the give tile coordinates.
QgsVectorTileMatrixSet & tileMatrixSet()
Returns the vector tile matrix set.
This class is responsible for decoding raw tile data written with Mapbox Vector Tiles encoding.
QStringList layerFieldNames(const QString &layerName) const
Returns a list of all field names in a tile. It can only be called after a successful decode()
bool decode(const QgsVectorTileRawData &rawTileData)
Tries to decode raw tile data, returns true on success.
QgsVectorTileFeatures layerFeatures(const QMap< QString, QgsFields > &perLayerFields, const QgsCoordinateTransform &ct, const QSet< QString > *layerSubset=nullptr) const
Returns decoded features grouped by sub-layers.
Keeps track of raw tile data from one or more sources that need to be decoded.
static QgsVectorLayer * makeVectorLayerForTile(QgsVectorTileLayer *mvt, QgsTileXYZ tileID, const QString &layerName)
Returns a temporary vector layer for given sub-layer of tile in vector tile layer.
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...
static void sortTilesByDistanceFromCenter(QVector< QgsTileXYZ > &tiles, QPointF center)
Orders tile requests according to the distance from view center (given in tile matrix coords)
static QPolygon tilePolygon(QgsTileXYZ id, const QgsCoordinateTransform &ct, const QgsTileMatrix &tm, const QgsMapToPixel &mtp)
Returns polygon (made by four corners of the tile) in screen coordinates.
static double scaleToZoom(double mapScale, double z0Scale=559082264.0287178)
Finds zoom level given map scale denominator.
static int scaleToZoomLevel(double mapScale, int sourceMinZoom, int sourceMaxZoom, double z0Scale=559082264.0287178)
Finds the best fitting zoom level given a map scale denominator and allowed zoom level range.
static void updateUriSources(QString &uri SIP_INOUT, bool forceUpdate=false)
Parses the style URL to update the source URLs in the uri.
static QgsFields makeQgisFields(const QSet< QString > &flds)
Returns QgsFields instance based on the set of field names.
static void loadSprites(const QVariantMap &styleDefinition, QgsMapBoxGlStyleConversionContext &context, const QString &styleUrl=QString())
Downloads the sprite image and sets it to the conversion context.
QList< QgsFeature > QgsFeatureList
#define QgsDebugMsgLevel(str, level)
#define QgsDebugError(str)
#define QgsSetRequestInitiatorClass(request, _class)
QMap< QString, QVector< QgsFeature > > QgsVectorTileFeatures
Features of a vector tile, grouped by sub-layer names (key of the map)
a helper class for ordering tile requests according to the distance from view center
bool operator()(QgsTileXYZ req1, QgsTileXYZ req2)
QPointF center
Center in tile matrix (!) coordinates.