QGIS API Documentation 3.38.0-Grenoble (exported)
Loading...
Searching...
No Matches
qgsvectortileutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsvectortileutils.cpp
3 --------------------------------------
4 Date : March 2020
5 Copyright : (C) 2020 by Martin Dobias
6 Email : wonder dot sk at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsvectortileutils.h"
17
18#include <math.h>
19
20#include <QPolygon>
21
24#include "qgsfields.h"
25#include "qgslogger.h"
26#include "qgsmaptopixel.h"
27#include "qgsrectangle.h"
28#include "qgsvectorlayer.h"
29
30#include "qgsvectortileloader.h"
32#include "qgsvectortilelayer.h"
38#include "qgsjsonutils.h"
39
40
42{
43 QgsRectangle r = tm.tileExtent( id );
44 QgsPointXY p00a = mtp.transform( ct.transform( r.xMinimum(), r.yMinimum() ) );
45 QgsPointXY p11a = mtp.transform( ct.transform( r.xMaximum(), r.yMaximum() ) );
46 QgsPointXY p01a = mtp.transform( ct.transform( r.xMinimum(), r.yMaximum() ) );
47 QgsPointXY p10a = mtp.transform( ct.transform( r.xMaximum(), r.yMinimum() ) );
48 QPolygon path;
49 path << p00a.toQPointF().toPoint();
50 path << p01a.toQPointF().toPoint();
51 path << p11a.toQPointF().toPoint();
52 path << p10a.toQPointF().toPoint();
53 return path;
54}
55
57{
58 QgsFields fields;
59 QStringList fieldsSorted = qgis::setToList( flds );
60 std::sort( fieldsSorted.begin(), fieldsSorted.end() );
61 for ( const QString &fieldName : std::as_const( fieldsSorted ) )
62 {
63 fields.append( QgsField( fieldName, QMetaType::Type::QString ) );
64 }
65 return fields;
66}
67
68double QgsVectorTileUtils::scaleToZoom( double mapScale, double z0Scale )
69{
70 double s0 = z0Scale;
71 double tileZoom2 = log( s0 / mapScale ) / log( 2 );
72 tileZoom2 -= 1; // TODO: it seems that map scale is double (is that because of high-dpi screen?)
73 return tileZoom2;
74}
75
76int QgsVectorTileUtils::scaleToZoomLevel( double mapScale, int sourceMinZoom, int sourceMaxZoom, double z0Scale )
77{
78 int tileZoom = static_cast<int>( round( scaleToZoom( mapScale, z0Scale ) ) );
79
80 if ( tileZoom < sourceMinZoom )
81 tileZoom = sourceMinZoom;
82 if ( tileZoom > sourceMaxZoom )
83 tileZoom = sourceMaxZoom;
84
85 return tileZoom;
86}
87
89{
90 QgsVectorTileMVTDecoder decoder( mvt->tileMatrixSet() );
91 const QgsVectorTileRawData rawTile = mvt->getRawTile( tileID );
92 decoder.decode( rawTile );
93 QSet<QString> fieldNames = qgis::listToSet( decoder.layerFieldNames( layerName ) );
94 fieldNames << QStringLiteral( "_geom_type" );
95 QMap<QString, QgsFields> perLayerFields;
96 QgsFields fields = QgsVectorTileUtils::makeQgisFields( fieldNames );
97 perLayerFields[layerName] = fields;
98 QgsVectorTileFeatures data = decoder.layerFeatures( perLayerFields, QgsCoordinateTransform() );
99 QgsFeatureList featuresList = data[layerName].toList();
100
101 // turn all geometries to geom. collections (otherwise they won't be accepted by memory provider)
102 for ( int i = 0; i < featuresList.count(); ++i )
103 {
104 QgsGeometry g = featuresList[i].geometry();
106 const QgsAbstractGeometry *gg = g.constGet();
107 if ( const QgsGeometryCollection *ggc = qgsgeometry_cast<const QgsGeometryCollection *>( gg ) )
108 {
109 for ( int k = 0; k < ggc->numGeometries(); ++k )
110 gc->addGeometry( ggc->geometryN( k )->clone() );
111 }
112 else
113 gc->addGeometry( gg->clone() );
114 featuresList[i].setGeometry( QgsGeometry( gc ) );
115 }
116
117 QgsVectorLayer *vl = new QgsVectorLayer( QStringLiteral( "GeometryCollection" ), layerName, QStringLiteral( "memory" ) );
118 vl->dataProvider()->addAttributes( fields.toList() );
119 vl->updateFields();
120 bool res = vl->dataProvider()->addFeatures( featuresList );
121 Q_UNUSED( res )
122 Q_ASSERT( res );
123 Q_ASSERT( featuresList.count() == vl->featureCount() );
124 vl->updateExtents();
125 QgsDebugMsgLevel( QStringLiteral( "Layer %1 features %2" ).arg( layerName ).arg( vl->featureCount() ), 2 );
126 return vl;
127}
128
129
130QString QgsVectorTileUtils::formatXYZUrlTemplate( const QString &url, QgsTileXYZ tile, const QgsTileMatrix &tileMatrix )
131{
132 QString turl( url );
133
134 turl.replace( QLatin1String( "{x}" ), QString::number( tile.column() ), Qt::CaseInsensitive );
135 if ( turl.contains( QLatin1String( "{-y}" ) ) )
136 {
137 turl.replace( QLatin1String( "{-y}" ), QString::number( tileMatrix.matrixHeight() - tile.row() - 1 ), Qt::CaseInsensitive );
138 }
139 else
140 {
141 turl.replace( QLatin1String( "{y}" ), QString::number( tile.row() ), Qt::CaseInsensitive );
142 }
143 turl.replace( QLatin1String( "{z}" ), QString::number( tile.zoomLevel() ), Qt::CaseInsensitive );
144 return turl;
145}
146
148{
149 return url.contains( QStringLiteral( "{x}" ) ) &&
150 ( url.contains( QStringLiteral( "{y}" ) ) || url.contains( QStringLiteral( "{-y}" ) ) ) &&
151 url.contains( QStringLiteral( "{z}" ) );
152}
153
156{
157 QPointF center;
159 {
160 QPointF p1( req1.column() + 0.5, req1.row() + 0.5 );
161 QPointF p2( req2.column() + 0.5, req2.row() + 0.5 );
162 // using chessboard distance (loading order more natural than euclidean/manhattan distance)
163 double d1 = std::max( std::fabs( center.x() - p1.x() ), std::fabs( center.y() - p1.y() ) );
164 double d2 = std::max( std::fabs( center.x() - p2.x() ), std::fabs( center.y() - p2.y() ) );
165 return d1 < d2;
166 }
167};
168
169void QgsVectorTileUtils::sortTilesByDistanceFromCenter( QVector<QgsTileXYZ> &tiles, QPointF center )
170{
172 cmp.center = center;
173 std::sort( tiles.begin(), tiles.end(), cmp );
174}
175
176void QgsVectorTileUtils::loadSprites( const QVariantMap &styleDefinition, QgsMapBoxGlStyleConversionContext &context, const QString &styleUrl )
177{
178 if ( styleDefinition.contains( QStringLiteral( "sprite" ) ) && ( context.spriteDefinitions().empty() || context.spriteImage().isNull() ) )
179 {
180 // retrieve sprite definition
181 QString spriteUriBase;
182 if ( styleDefinition.value( QStringLiteral( "sprite" ) ).toString().startsWith( QLatin1String( "http" ) ) )
183 {
184 spriteUriBase = styleDefinition.value( QStringLiteral( "sprite" ) ).toString();
185 }
186 else
187 {
188 spriteUriBase = styleUrl + '/' + styleDefinition.value( QStringLiteral( "sprite" ) ).toString();
189 }
190
191 for ( int resolution = 2; resolution > 0; resolution-- )
192 {
193 QUrl spriteUrl = QUrl( spriteUriBase );
194 spriteUrl.setPath( spriteUrl.path() + QStringLiteral( "%1.json" ).arg( resolution > 1 ? QStringLiteral( "@%1x" ).arg( resolution ) : QString() ) );
195 QNetworkRequest request = QNetworkRequest( spriteUrl );
196 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsVectorTileLayer" ) )
197 QgsBlockingNetworkRequest networkRequest;
198 switch ( networkRequest.get( request ) )
199 {
201 {
202 const QgsNetworkReplyContent content = networkRequest.reply();
203 const QVariantMap spriteDefinition = QgsJsonUtils::parseJson( content.content() ).toMap();
204
205 // retrieve sprite images
206 QUrl spriteUrl = QUrl( spriteUriBase );
207 spriteUrl.setPath( spriteUrl.path() + QStringLiteral( "%1.png" ).arg( resolution > 1 ? QStringLiteral( "@%1x" ).arg( resolution ) : QString() ) );
208 QNetworkRequest request = QNetworkRequest( spriteUrl );
209 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsVectorTileLayer" ) )
210 QgsBlockingNetworkRequest networkRequest;
211 switch ( networkRequest.get( request ) )
212 {
214 {
215 const QgsNetworkReplyContent imageContent = networkRequest.reply();
216 const QImage spriteImage( QImage::fromData( imageContent.content() ) );
217 context.setSprites( spriteImage, spriteDefinition );
218 break;
219 }
220
224 break;
225 }
226
227 break;
228 }
229
233 break;
234 }
235
236 if ( !context.spriteDefinitions().isEmpty() )
237 break;
238 }
239 }
240}
241
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...
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr)
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...
Class for doing transforms between two map coordinate systems.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:53
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:60
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.
Definition qgspointxy.h:60
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:166
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 *.
Definition qgstiles.h:134
QgsRectangle tileExtent(QgsTileXYZ id) const
Returns extent of the given tile in this matrix.
Definition qgstiles.cpp:81
int matrixHeight() const
Returns number of rows of the tile matrix.
Definition qgstiles.h:186
Stores coordinates of a tile in a tile matrix set.
Definition qgstiles.h:38
int zoomLevel() const
Returns tile's zoom level (Z)
Definition qgstiles.h:51
int column() const
Returns tile's column index (X)
Definition qgstiles.h:47
int row() const
Returns tile's row index (Y)
Definition qgstiles.h:49
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 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 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)
Definition qgslogger.h:39
#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.