QGIS API Documentation 3.30.0-'s-Hertogenbosch (f186b8efe0)
qgsmapsettings.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsmapsettings.cpp
3 --------------------------------------
4 Date : December 2013
5 Copyright : (C) 2013 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 "qgsmapsettings.h"
17
18#include "qgsscalecalculator.h"
19#include "qgsmaptopixel.h"
20#include "qgslogger.h"
21
22#include "qgsmessagelog.h"
23#include "qgsmaplayer.h"
25#include "qgsxmlutils.h"
26#include "qgsexception.h"
27#include "qgsgeometry.h"
28#include "qgsgrouplayer.h"
30#include "qgsellipsoidutils.h"
31#include "qgsunittypes.h"
32
33Q_GUI_EXPORT extern int qt_defaultDpiX();
34
35
37 : mDpi( qt_defaultDpiX() ) // DPI that will be used by default for QImage instances
38 , mSize( QSize( 0, 0 ) )
39 , mBackgroundColor( Qt::white )
40 , mSelectionColor( Qt::yellow )
41 , mFlags( Qgis::MapSettingsFlag::Antialiasing | Qgis::MapSettingsFlag::UseAdvancedEffects | Qgis::MapSettingsFlag::DrawLabeling | Qgis::MapSettingsFlag::DrawSelection )
42 , mSegmentationTolerance( M_PI_2 / 90 )
43{
44 mScaleCalculator.setMapUnits( Qgis::DistanceUnit::Unknown );
46
48}
49
50void QgsMapSettings::setMagnificationFactor( double factor, const QgsPointXY *center )
51{
52 const double ratio = mMagnificationFactor / factor;
53
54 mMagnificationFactor = factor;
55
56 const double rot = rotation();
57 setRotation( 0.0 );
58
60 ext.scale( ratio, center );
61
62 mRotation = rot;
63 mExtent = ext;
64 mDpi = mDpi / ratio;
65
66 QgsDebugMsgLevel( QStringLiteral( "Magnification factor: %1 dpi: %2 ratio: %3" ).arg( factor ).arg( mDpi ).arg( ratio ), 3 );
67
69}
70
72{
74}
75
77{
78 return mExtent;
79}
80
81void QgsMapSettings::setExtent( const QgsRectangle &extent, bool magnified )
82{
83 QgsRectangle magnifiedExtent = extent;
84
85 if ( !magnified )
86 magnifiedExtent.scale( 1 / mMagnificationFactor );
87
88 mExtent = magnifiedExtent;
89
91}
92
94{
95 return mExtentBuffer;
96}
97
98void QgsMapSettings::setExtentBuffer( const double buffer )
99{
100 mExtentBuffer = buffer;
101}
102
104{
105 return mRotation;
106}
107
108void QgsMapSettings::setRotation( double degrees )
109{
110 if ( qgsDoubleNear( mRotation, degrees ) )
111 return;
112
113 mRotation = degrees;
114
115 // TODO: update extent while keeping scale ?
117}
118
119
121{
123
124 if ( extent.isEmpty() || !extent.isFinite() )
125 {
126 mValid = false;
127 return;
128 }
129
130 // Don't allow zooms where the current extent is so small that it
131 // can't be accurately represented using a double (which is what
132 // currentExtent uses). Excluding 0 avoids a divide by zero and an
133 // infinite loop when rendering to a new canvas. Excluding extents
134 // greater than 1 avoids doing unnecessary calculations.
135
136 // The scheme is to compare the width against the mean x coordinate
137 // (and height against mean y coordinate) and only allow zooms where
138 // the ratio indicates that there is more than about 12 significant
139 // figures (there are about 16 significant figures in a double).
140
141 if ( extent.width() > 0 &&
142 extent.height() > 0 &&
143 extent.width() < 1 &&
144 extent.height() < 1 )
145 {
146 // Use abs() on the extent to avoid the case where the extent is
147 // symmetrical about 0.
148 const double xMean = ( std::fabs( extent.xMinimum() ) + std::fabs( extent.xMaximum() ) ) * 0.5;
149 const double yMean = ( std::fabs( extent.yMinimum() ) + std::fabs( extent.yMaximum() ) ) * 0.5;
150
151 const double xRange = extent.width() / xMean;
152 const double yRange = extent.height() / yMean;
153
154 static const double MIN_PROPORTION = 1e-12;
155 if ( xRange < MIN_PROPORTION || yRange < MIN_PROPORTION )
156 {
157 mValid = false;
158 return;
159 }
160 }
161
162 const double myHeight = mSize.height();
163 const double myWidth = mSize.width();
164
165 if ( !myWidth || !myHeight )
166 {
167 mValid = false;
168 return;
169 }
170
171 // calculate the translation and scaling parameters
172 const double mapUnitsPerPixelY = mExtent.height() / myHeight;
173 const double mapUnitsPerPixelX = mExtent.width() / myWidth;
174 mMapUnitsPerPixel = mapUnitsPerPixelY > mapUnitsPerPixelX ? mapUnitsPerPixelY : mapUnitsPerPixelX;
175
176 // calculate the actual extent of the mapCanvas
177 double dxmin = mExtent.xMinimum(), dxmax = mExtent.xMaximum(),
178 dymin = mExtent.yMinimum(), dymax = mExtent.yMaximum(), whitespace;
179
180 if ( mapUnitsPerPixelY > mapUnitsPerPixelX )
181 {
182 whitespace = ( ( myWidth * mMapUnitsPerPixel ) - mExtent.width() ) * 0.5;
183 dxmin -= whitespace;
184 dxmax += whitespace;
185 }
186 else
187 {
188 whitespace = ( ( myHeight * mMapUnitsPerPixel ) - mExtent.height() ) * 0.5;
189 dymin -= whitespace;
190 dymax += whitespace;
191 }
192
193 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
194
195 // update the scale
198
199 bool ok = true;
202 visibleExtent().center().x(),
203 visibleExtent().center().y(),
204 outputSize().width(),
205 outputSize().height(),
206 mRotation, &ok );
207
208 mValid = ok;
209
210#if 1 // set visible extent taking rotation in consideration
211 if ( mRotation )
212 {
213 const QgsPointXY p1 = mMapToPixel.toMapCoordinates( QPoint( 0, 0 ) );
214 const QgsPointXY p2 = mMapToPixel.toMapCoordinates( QPoint( 0, myHeight ) );
215 const QgsPointXY p3 = mMapToPixel.toMapCoordinates( QPoint( myWidth, 0 ) );
216 const QgsPointXY p4 = mMapToPixel.toMapCoordinates( QPoint( myWidth, myHeight ) );
217 dxmin = std::min( p1.x(), std::min( p2.x(), std::min( p3.x(), p4.x() ) ) );
218 dymin = std::min( p1.y(), std::min( p2.y(), std::min( p3.y(), p4.y() ) ) );
219 dxmax = std::max( p1.x(), std::max( p2.x(), std::max( p3.x(), p4.x() ) ) );
220 dymax = std::max( p1.y(), std::max( p2.y(), std::max( p3.y(), p4.y() ) ) );
221 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
222 }
223#endif
224
225 QgsDebugMsgLevel( QStringLiteral( "Map units per pixel (x,y) : %1, %2" ).arg( qgsDoubleToString( mapUnitsPerPixelX ), qgsDoubleToString( mapUnitsPerPixelY ) ), 5 );
226 QgsDebugMsgLevel( QStringLiteral( "Pixmap dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mSize.width() ), qgsDoubleToString( mSize.height() ) ), 5 );
227 QgsDebugMsgLevel( QStringLiteral( "Extent dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mExtent.width() ), qgsDoubleToString( mExtent.height() ) ), 5 );
229 QgsDebugMsgLevel( QStringLiteral( "Adjusted map units per pixel (x,y) : %1, %2" ).arg( qgsDoubleToString( mVisibleExtent.width() / myWidth ), qgsDoubleToString( mVisibleExtent.height() / myHeight ) ), 5 );
230 QgsDebugMsgLevel( QStringLiteral( "Recalced pixmap dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mVisibleExtent.width() / mMapUnitsPerPixel ), qgsDoubleToString( mVisibleExtent.height() / mMapUnitsPerPixel ) ), 5 );
231 QgsDebugMsgLevel( QStringLiteral( "Scale (assuming meters as map units) = 1:%1" ).arg( qgsDoubleToString( mScale ) ), 5 );
232 QgsDebugMsgLevel( QStringLiteral( "Rotation: %1 degrees" ).arg( mRotation ), 5 );
233 QgsDebugMsgLevel( QStringLiteral( "Extent: %1" ).arg( mExtent.asWktCoordinates() ), 5 );
234 QgsDebugMsgLevel( QStringLiteral( "Visible Extent: %1" ).arg( mVisibleExtent.asWktCoordinates() ), 5 );
235 QgsDebugMsgLevel( QStringLiteral( "Magnification factor: %1" ).arg( mMagnificationFactor ), 5 );
236
237}
238
239
241{
242 return mSize;
243}
244
246{
247 mSize = size;
248
250}
251
253{
254 return mDevicePixelRatio;
255}
256
258{
259 mDevicePixelRatio = dpr;
261}
262
264{
265 return outputSize() * mDevicePixelRatio;
266}
267
269{
270 return mDpi;
271}
272
274{
275 mDpi = dpi;
276
278}
279
281{
282 return mDpiTarget;
283}
284
286{
287 mDpiTarget = dpi;
288}
289
290QStringList QgsMapSettings::layerIds( bool expandGroupLayers ) const
291{
292 const QList<QgsMapLayer * > mapLayers = layers( expandGroupLayers );
293 QStringList res;
294 res.reserve( mapLayers.size() );
295 for ( const QgsMapLayer *layer : mapLayers )
296 res << layer->id();
297 return res;
298}
299
300QList<QgsMapLayer *> QgsMapSettings::layers( bool expandGroupLayers ) const
301{
302 const QList<QgsMapLayer *> actualLayers = _qgis_listQPointerToRaw( mLayers );
303 if ( !expandGroupLayers )
304 return actualLayers;
305
306 QList< QgsMapLayer * > result;
307
308 std::function< void( const QList< QgsMapLayer * >& layers ) > expandLayers;
309 expandLayers = [&result, &expandLayers]( const QList< QgsMapLayer * > &layers )
310 {
311 for ( QgsMapLayer *layer : layers )
312 {
313 if ( QgsGroupLayer *groupLayer = qobject_cast< QgsGroupLayer * >( layer ) )
314 {
315 expandLayers( groupLayer->childLayers() );
316 }
317 else
318 {
319 result << layer;
320 }
321 }
322 };
323
324 expandLayers( actualLayers );
325 return result;
326}
327
328void QgsMapSettings::setLayers( const QList<QgsMapLayer *> &layers )
329{
330 // filter list, removing null layers and non-spatial layers
331 auto filteredList = layers;
332 filteredList.erase( std::remove_if( filteredList.begin(), filteredList.end(),
333 []( QgsMapLayer * layer )
334 {
335 return !layer || !layer->isSpatial();
336 } ), filteredList.end() );
337
338 mLayers = _qgis_listRawToQPointer( filteredList );
339}
340
341QMap<QString, QString> QgsMapSettings::layerStyleOverrides() const
342{
344}
345
346void QgsMapSettings::setLayerStyleOverrides( const QMap<QString, QString> &overrides )
347{
348 mLayerStyleOverrides = overrides;
349}
350
352{
353 mDestCRS = crs;
355 // Since the map units have changed, force a recalculation of the scale.
357}
358
360{
361 return mDestCRS;
362}
363
364bool QgsMapSettings::setEllipsoid( const QString &ellipsoid )
365{
367 if ( !params.valid )
368 {
369 return false;
370 }
371 else
372 {
374 return true;
375 }
376}
377
378void QgsMapSettings::setFlags( Qgis::MapSettingsFlags flags )
379{
380 mFlags = flags;
381}
382
384{
385 if ( on )
386 mFlags |= flag;
387 else
388 mFlags &= ~( static_cast< int >( flag ) );
389}
390
391Qgis::MapSettingsFlags QgsMapSettings::flags() const
392{
393 return mFlags;
394}
395
397{
398 return mFlags.testFlag( flag );
399}
400
402{
403 return mScaleCalculator.mapUnits();
404}
405
406
408{
409 return mValid;
410}
411
413{
414 return mVisibleExtent;
415}
416
418{
419 QPolygonF poly;
420
421 const QSize &sz = outputSize();
422 const QgsMapToPixel &m2p = mapToPixel();
423
424 poly << m2p.toMapCoordinates( 0.0, 0.0 ).toQPointF();
425 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), 0.0 ).toQPointF();
426 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), static_cast<double>( sz.height() ) ).toQPointF();
427 poly << m2p.toMapCoordinates( 0.0, static_cast<double>( sz.height() ) ).toQPointF();
428
429 return poly;
430}
431
433{
434 QPolygonF poly;
435
436 const QSize &sz = outputSize();
437 const QgsMapToPixel &m2p = mapToPixel();
438
439 // Transform tilebuffer in pixel.
440 // Original tilebuffer is in pixel and transformed only according
441 // extent width (see QgsWmsRenderContext::mapTileBuffer)
442
443 const double mapUnitsPerPixel = mExtent.width() / sz.width();
444 const double buffer = mExtentBuffer / mapUnitsPerPixel;
445
446 poly << m2p.toMapCoordinates( -buffer, -buffer ).toQPointF();
447 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), -buffer ).toQPointF();
448 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), static_cast<double>( sz.height() + buffer ) ).toQPointF();
449 poly << m2p.toMapCoordinates( -buffer, static_cast<double>( sz.height() + buffer ) ).toQPointF();
450
451 return poly;
452}
453
455{
456 return mMapUnitsPerPixel;
457}
458
460{
461 return mScale;
462}
463
465{
466#ifdef QGISDEBUG
467 if ( !mHasTransformContext )
468 QgsDebugMsgLevel( QStringLiteral( "No QgsCoordinateTransformContext context set for transform" ), 4 );
469#endif
470
471 return mTransformContext;
472}
473
475{
476 mTransformContext = context;
477#ifdef QGISDEBUG
478 mHasTransformContext = true;
479#endif
480}
481
483{
484 if ( !layer )
485 return QgsCoordinateTransform();
486
488}
489
491{
492 // Output width in inches
493 const double outputWidthInInches = outputSize().width() / outputDpi();
494
495 // Desired visible width (honouring scale)
496 const double scaledWidthInInches = outputWidthInInches * scale;
497
498 if ( mapUnits() == Qgis::DistanceUnit::Degrees )
499 {
500 // Start with some fraction of the current extent around the center
501 const double delta = mExtent.width() / 100.;
502 QgsRectangle ext( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
503 // Get scale at extent, and then scale extent to the desired scale
504 const double testScale = mScaleCalculator.calculate( ext, outputSize().width() );
505 ext.scale( scale / testScale );
506 return ext;
507 }
508 else
509 {
510 // Conversion from inches to mapUnits - this is safe to use, because we know here that the map units AREN'T in degrees
511 const double conversionFactor = QgsUnitTypes::fromUnitToUnitFactor( Qgis::DistanceUnit::Feet, mapUnits() ) / 12;
512
513 const double delta = 0.5 * scaledWidthInInches * conversionFactor;
514 return QgsRectangle( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
515 }
516}
517
519{
520 return mScaleCalculator.calculate( extent, outputSize().width() );
521}
522
523double QgsMapSettings::layerToMapUnits( const QgsMapLayer *layer, const QgsRectangle &referenceExtent ) const
524{
525 return layerTransform( layer ).scaleFactor( referenceExtent );
526}
527
528
530{
531 try
532 {
534 if ( ct.isValid() )
535 {
536 QgsDebugMsgLevel( QStringLiteral( "sourceCrs = %1" ).arg( ct.sourceCrs().authid() ), 3 );
537 QgsDebugMsgLevel( QStringLiteral( "destCRS = %1" ).arg( ct.destinationCrs().authid() ), 3 );
538 QgsDebugMsgLevel( QStringLiteral( "extent %1" ).arg( extent.toString() ), 3 );
541 }
542 }
543 catch ( QgsCsException &cse )
544 {
545 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
546 }
547
548 QgsDebugMsgLevel( QStringLiteral( "proj extent = %1 " ).arg( extent.toString() ), 3 );
549
550 return extent;
551}
552
553
555{
556 try
557 {
560 if ( ct.isValid() )
561 {
562 QgsDebugMsgLevel( QStringLiteral( "sourceCrs = %1" ).arg( ct.sourceCrs().authid() ), 3 );
563 QgsDebugMsgLevel( QStringLiteral( "destCRS = %1" ).arg( ct.destinationCrs().authid() ), 3 );
564 QgsDebugMsgLevel( QStringLiteral( "extent = %1" ).arg( extent.toString() ), 3 );
565 extent = ct.transformBoundingBox( extent, Qgis::TransformDirection::Reverse );
566 }
567 }
568 catch ( QgsCsException &cse )
569 {
570 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
571 }
572
573 QgsDebugMsgLevel( QStringLiteral( "proj extent = %1" ).arg( extent.toString() ), 3 );
574
575 return extent;
576}
577
578
580{
581 try
582 {
583 const QgsCoordinateTransform ct = layerTransform( layer );
584 if ( ct.isValid() )
585 point = ct.transform( point, Qgis::TransformDirection::Forward );
586 }
587 catch ( QgsCsException &cse )
588 {
589 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
590 }
591
592 return point;
593}
594
596{
597 double x = point.x();
598 double y = point.y();
599 double z = point.z();
600 const double m = point.m();
601
602 try
603 {
604 const QgsCoordinateTransform ct = layerTransform( layer );
605 if ( ct.isValid() )
606 ct.transformInPlace( x, y, z, Qgis::TransformDirection::Forward );
607 }
608 catch ( QgsCsException &cse )
609 {
610 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
611 }
612
613 return QgsPoint( x, y, z, m );
614}
615
616
618{
619 try
620 {
621 const QgsCoordinateTransform ct = layerTransform( layer );
622 if ( ct.isValid() )
623 rect = ct.transform( rect, Qgis::TransformDirection::Forward );
624 }
625 catch ( QgsCsException &cse )
626 {
627 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
628 }
629
630 return rect;
631}
632
633
635{
636 try
637 {
638 const QgsCoordinateTransform ct = layerTransform( layer );
639 if ( ct.isValid() )
640 point = ct.transform( point, Qgis::TransformDirection::Reverse );
641 }
642 catch ( QgsCsException &cse )
643 {
644 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
645 }
646
647 return point;
648}
649
651{
652 double x = point.x();
653 double y = point.y();
654 double z = point.z();
655 const double m = point.m();
656
657 try
658 {
659 const QgsCoordinateTransform ct = layerTransform( layer );
660 if ( ct.isValid() )
661 ct.transformInPlace( x, y, z, Qgis::TransformDirection::Reverse );
662 }
663 catch ( QgsCsException &cse )
664 {
665 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
666 }
667
668 return QgsPoint( x, y, z, m );
669}
670
671
673{
674 try
675 {
676 const QgsCoordinateTransform ct = layerTransform( layer );
677 if ( ct.isValid() )
678 rect = ct.transform( rect, Qgis::TransformDirection::Reverse );
679 }
680 catch ( QgsCsException &cse )
681 {
682 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
683 }
684
685 return rect;
686}
687
688
689
691{
692 // reset the map canvas extent since the extent may now be smaller
693 // We can't use a constructor since QgsRectangle normalizes the rectangle upon construction
696
697 // iterate through the map layers and test each layers extent
698 // against the current min and max values
699 QgsDebugMsgLevel( QStringLiteral( "Layer count: %1" ).arg( mLayers.count() ), 5 );
700 const auto constMLayers = mLayers;
701 for ( const QgsWeakMapLayerPointer &layerPtr : constMLayers )
702 {
703 if ( QgsMapLayer *lyr = layerPtr.data() )
704 {
705 QgsDebugMsgLevel( "Updating extent using " + lyr->name(), 5 );
706 QgsDebugMsgLevel( "Input extent: " + lyr->extent().toString(), 5 );
707
708 if ( lyr->extent().isNull() )
709 continue;
710
711 // Layer extents are stored in the coordinate system (CS) of the
712 // layer. The extent must be projected to the canvas CS
713 const QgsRectangle extent = layerExtentToOutputExtent( lyr, lyr->extent() );
714
715 QgsDebugMsgLevel( "Output extent: " + extent.toString(), 5 );
717 }
718 }
719
720 if ( fullExtent.width() == 0.0 || fullExtent.height() == 0.0 )
721 {
722 // If all of the features are at the one point, buffer the
723 // rectangle a bit. If they are all at zero, do something a bit
724 // more crude.
725
726 if ( fullExtent.xMinimum() == 0.0 && fullExtent.xMaximum() == 0.0 &&
727 fullExtent.yMinimum() == 0.0 && fullExtent.yMaximum() == 0.0 )
728 {
729 fullExtent.set( -1.0, -1.0, 1.0, 1.0 );
730 }
731 else
732 {
733 const double padFactor = 1e-8;
734 const double widthPad = fullExtent.xMinimum() * padFactor;
735 const double heightPad = fullExtent.yMinimum() * padFactor;
736 const double xmin = fullExtent.xMinimum() - widthPad;
737 const double xmax = fullExtent.xMaximum() + widthPad;
738 const double ymin = fullExtent.yMinimum() - heightPad;
739 const double ymax = fullExtent.yMaximum() + heightPad;
740 fullExtent.set( xmin, ymin, xmax, ymax );
741 }
742 }
743
744 QgsDebugMsgLevel( "Full extent: " + fullExtent.toString(), 5 );
745 return fullExtent;
746}
747
748
749void QgsMapSettings::readXml( QDomNode &node )
750{
751 // set destination CRS
753 const QDomNode srsNode = node.namedItem( QStringLiteral( "destinationsrs" ) );
754 if ( !srsNode.isNull() )
755 {
756 srs.readXml( srsNode );
757 }
758 setDestinationCrs( srs );
759
760 // set extent
761 const QDomNode extentNode = node.namedItem( QStringLiteral( "extent" ) );
762 const QgsRectangle aoi = QgsXmlUtils::readRectangle( extentNode.toElement() );
763 setExtent( aoi );
764
765 // set rotation
766 const QDomNode rotationNode = node.namedItem( QStringLiteral( "rotation" ) );
767 const QString rotationVal = rotationNode.toElement().text();
768 if ( ! rotationVal.isEmpty() )
769 {
770 const double rot = rotationVal.toDouble();
771 setRotation( rot );
772 }
773
774 //render map tile
775 const QDomElement renderMapTileElem = node.firstChildElement( QStringLiteral( "rendermaptile" ) );
776 if ( !renderMapTileElem.isNull() )
777 {
778 setFlag( Qgis::MapSettingsFlag::RenderMapTile, renderMapTileElem.text() == QLatin1String( "1" ) );
779 }
780}
781
782
783
784void QgsMapSettings::writeXml( QDomNode &node, QDomDocument &doc )
785{
786 // units
787 node.appendChild( QgsXmlUtils::writeMapUnits( mapUnits(), doc ) );
788
789 // Write current view extents
790 node.appendChild( QgsXmlUtils::writeRectangle( extent(), doc ) );
791
792 // Write current view rotation
793 QDomElement rotNode = doc.createElement( QStringLiteral( "rotation" ) );
794 rotNode.appendChild(
795 doc.createTextNode( qgsDoubleToString( rotation() ) )
796 );
797 node.appendChild( rotNode );
798
799 // destination CRS
800 if ( mDestCRS.isValid() )
801 {
802 QDomElement srsNode = doc.createElement( QStringLiteral( "destinationsrs" ) );
803 node.appendChild( srsNode );
804 mDestCRS.writeXml( srsNode, doc );
805 }
806
807 //render map tile
808 QDomElement renderMapTileElem = doc.createElement( QStringLiteral( "rendermaptile" ) );
809 const QDomText renderMapTileText = doc.createTextNode( testFlag( Qgis::MapSettingsFlag::RenderMapTile ) ? "1" : "0" );
810 renderMapTileElem.appendChild( renderMapTileText );
811 node.appendChild( renderMapTileElem );
812}
813
815{
817}
818
820{
821 mLabelBoundaryGeometry = boundary;
822}
823
825{
826 mClippingRegions.append( region );
827}
828
829void QgsMapSettings::setClippingRegions( const QList<QgsMapClippingRegion> &regions )
830{
831 mClippingRegions = regions;
832}
833
834QList<QgsMapClippingRegion> QgsMapSettings::clippingRegions() const
835{
836 return mClippingRegions;
837}
838
840{
841 mRenderedFeatureHandlers.append( handler );
842}
843
844QList<QgsRenderedFeatureHandlerInterface *> QgsMapSettings::renderedFeatureHandlers() const
845{
846 return mRenderedFeatureHandlers;
847}
848
850{
851 return mZRange;
852}
853
855{
856 mZRange = zRange;
857}
858
860{
861 return mRendererUsage;
862}
863
865{
867}
868
870{
871 return mFrameRate;
872}
873
875{
876 mFrameRate = rate;
877}
878
880{
881 return mCurrentFrame;
882}
883
884void QgsMapSettings::setCurrentFrame( long long frame )
885{
886 mCurrentFrame = frame;
887}
888
890{
891 return mShadingRenderer;
892}
893
895{
897}
The Qgis class provides global constants for use throughout the application.
Definition: qgis.h:55
DistanceUnit
Units of distance.
Definition: qgis.h:3047
RendererUsage
Usage of the renderer.
Definition: qgis.h:2205
MapSettingsFlag
Coordinate transformation flags.
Definition: qgis.h:1663
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
This class represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
Q_GADGET Qgis::DistanceUnit mapUnits
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
bool writeXml(QDomNode &node, QDomDocument &doc) const
Stores state to the given Dom node in the given document.
Contains information about the context in which a coordinate transform is executed.
Class for doing transforms between two map coordinate systems.
QgsCoordinateReferenceSystem sourceCrs() const
Returns the source coordinate reference system, which the transform will transform coordinates from.
void setBallparkTransformsAreAppropriate(bool appropriate)
Sets whether approximate "ballpark" results are appropriate for this coordinate transform.
double scaleFactor(const QgsRectangle &referenceExtent) const
Computes an estimated conversion factor between source and destination units:
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
void transformInPlace(double &x, double &y, double &z, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const SIP_THROW(QgsCsException)
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system, which the transform will transform coordinates t...
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const SIP_THROW(QgsCsException)
Transforms a rectangle from the source CRS to the destination CRS.
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const SIP_THROW(QgsCsException)
Transform the point from the source CRS to the destination CRS.
Custom exception class for Coordinate Reference System related exceptions.
Definition: qgsexception.h:66
QgsRange which stores a range of double values.
Definition: qgsrange.h:203
This class can render elevation shading on an image with different methods (eye dome lighting,...
static EllipsoidParameters ellipsoidParameters(const QString &ellipsoid)
Returns the parameters for the specified ellipsoid.
QString what() const
Definition: qgsexception.h:48
A geometry is the spatial representation of a feature.
Definition: qgsgeometry.h:164
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
Definition: qgsgrouplayer.h:42
A map clipping region (in map coordinates and CRS).
Base class for all map layer types.
Definition: qgsmaplayer.h:73
QgsCoordinateReferenceSystem crs
Definition: qgsmaplayer.h:79
void setElevationShadingRenderer(const QgsElevationShadingRenderer &renderer)
Sets the shading renderer used to render shading on the entire map.
QSize deviceOutputSize() const
Returns the device output size of the map render.
Qgis::DistanceUnit mapUnits() const
Returns the units of the map's geographical coordinates - used for scale calculation.
Qgis::RendererUsage rendererUsage() const
Returns the rendering usage.
QgsVectorSimplifyMethod mSimplifyMethod
void addClippingRegion(const QgsMapClippingRegion &region)
Adds a new clipping region to the map settings.
void writeXml(QDomNode &node, QDomDocument &doc)
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
QList< QgsMapLayer * > layers(bool expandGroupLayers=false) const
Returns the list of layers which will be rendered in the map.
Qgis::RendererUsage mRendererUsage
QgsRectangle mVisibleExtent
Extent with some additional white space that matches the output aspect ratio.
QPolygonF visiblePolygon() const
Returns the visible area as a polygon (may be rotated)
void addRenderedFeatureHandler(QgsRenderedFeatureHandlerInterface *handler)
Adds a rendered feature handler to use while rendering the map settings.
void setLayers(const QList< QgsMapLayer * > &layers)
Sets the list of layers to render in the map.
double scale() const
Returns the calculated map scale.
void setFrameRate(double rate)
Sets the frame rate of the map (in frames per second), for maps which are part of an animation.
void setFlags(Qgis::MapSettingsFlags flags)
Sets combination of flags that will be used for rendering.
Qgis::MapSettingsFlags mFlags
QgsCoordinateTransform layerTransform(const QgsMapLayer *layer) const
Returns the coordinate transform from layer's CRS to destination CRS.
QgsRectangle layerExtentToOutputExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from layer's CRS to output CRS
QgsDoubleRange zRange() const
Returns the range of z-values which will be visible in the map.
bool setEllipsoid(const QString &ellipsoid)
Sets the ellipsoid by its acronym.
void setDpiTarget(double dpi)
Sets the target dpi (dots per inch) to be taken into consideration when rendering.
double magnificationFactor() const
Returns the magnification factor.
double mMapUnitsPerPixel
QgsGeometry labelBoundaryGeometry() const
Returns the label boundary geometry, which restricts where in the rendered map labels are permitted t...
QList< QgsRenderedFeatureHandlerInterface * > renderedFeatureHandlers() const
Returns the list of rendered feature handlers to use while rendering the map settings.
QStringList layerIds(bool expandGroupLayers=false) const
Returns the list of layer IDs which will be rendered in the map.
void setDevicePixelRatio(float dpr)
Sets the device pixel ratio.
QString mEllipsoid
ellipsoid acronym (from table tbl_ellipsoids)
void setZRange(const QgsDoubleRange &range)
Sets the range of z-values which will be visible in the map.
double dpiTarget() const
Returns the target DPI (dots per inch) to be taken into consideration when rendering.
long long currentFrame() const
Returns the current frame number of the map, for maps which are part of an animation.
bool mValid
Whether the actual settings are valid (set in updateDerived())
void setOutputDpi(double dpi)
Sets the dpi (dots per inch) used for conversion between real world units (e.g.
const QgsMapToPixel & mapToPixel() const
double mapUnitsPerPixel() const
Returns the distance in geographical coordinates that equals to one pixel in the map.
void setRendererUsage(Qgis::RendererUsage rendererUsage)
Sets the rendering usage.
float devicePixelRatio() const
Returns the device pixel ratio.
QgsRectangle mExtent
QSize outputSize() const
Returns the size of the resulting map image, in pixels.
QgsRectangle extent() const
Returns geographical coordinates of the rectangle that should be rendered.
QMap< QString, QString > mLayerStyleOverrides
QgsGeometry mLabelBoundaryGeometry
void setLayerStyleOverrides(const QMap< QString, QString > &overrides)
Sets the map of map layer style overrides (key: layer ID, value: style name) where a different style ...
QgsElevationShadingRenderer mShadingRenderer
QgsCoordinateTransformContext mTransformContext
void setExtent(const QgsRectangle &rect, bool magnified=true)
Sets the coordinates of the rectangle which should be rendered.
void setClippingRegions(const QList< QgsMapClippingRegion > &regions)
Sets the list of clipping regions to apply to the map.
double layerToMapUnits(const QgsMapLayer *layer, const QgsRectangle &referenceExtent=QgsRectangle()) const
Computes an estimated conversion factor between layer and map units: layerUnits * layerToMapUnits = m...
double extentBuffer() const
Returns the buffer in map units to use around the visible extent for rendering symbols whose correspo...
QgsScaleCalculator mScaleCalculator
Qgis::MapSettingsFlags flags() const
Returns combination of flags used for rendering.
double frameRate() const
Returns the frame rate of the map (in frames per second), for maps which are part of an animation.
void setExtentBuffer(double buffer)
Sets the buffer in map units to use around the visible extent for rendering symbols whose correspondi...
QgsRectangle visibleExtent() const
Returns the actual extent derived from requested extent that takes output image size into account.
QgsRectangle outputExtentToLayerExtent(const QgsMapLayer *layer, QgsRectangle extent) const
transform bounding box from output CRS to layer's CRS
QgsRectangle fullExtent() const
returns current extent of layer set
void setTransformContext(const QgsCoordinateTransformContext &context)
Sets the coordinate transform context, which stores various information regarding which datum transfo...
void setRotation(double rotation)
Sets the rotation of the resulting map image, in degrees clockwise.
double computeScaleForExtent(const QgsRectangle &extent) const
Compute the scale that corresponds to the specified extent.
QString ellipsoid() const
Returns ellipsoid's acronym.
double mMagnificationFactor
void setCurrentFrame(long long frame)
Sets the current frame of the map, for maps which are part of an animation.
const QgsElevationShadingRenderer & elevationShadingRenderer() const
Returns the shading renderer used to render shading on the entire map.
QgsCoordinateReferenceSystem mDestCRS
double outputDpi() const
Returns the DPI (dots per inch) used for conversion between real world units (e.g.
void setLabelBoundaryGeometry(const QgsGeometry &boundary)
Sets the label boundary geometry, which restricts where in the rendered map labels are permitted to b...
QgsMapToPixel mMapToPixel
bool testFlag(Qgis::MapSettingsFlag flag) const
Check whether a particular flag is enabled.
QMap< QString, QString > layerStyleOverrides() const
Returns the map of map layer style overrides (key: layer ID, value: style name) where a different sty...
double rotation() const
Returns the rotation of the resulting map image, in degrees clockwise.
QList< QgsMapClippingRegion > clippingRegions() const
Returns the list of clipping regions to apply to the map.
bool hasValidSettings() const
Check whether the map settings are valid and can be used for rendering.
QgsWeakMapLayerPointerList mLayers
list of layers to be rendered (stored as weak pointers)
void setOutputSize(QSize size)
Sets the size of the resulting map image, in pixels.
QgsPointXY mapToLayerCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from output CRS to layer's CRS
long long mCurrentFrame
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system for the map render.
QPolygonF visiblePolygonWithBuffer() const
Returns the visible area as a polygon (may be rotated) with extent buffer included.
void setFlag(Qgis::MapSettingsFlag flag, bool on=true)
Enable or disable a particular flag (other flags are not affected)
void setDestinationCrs(const QgsCoordinateReferenceSystem &crs)
Sets the destination crs (coordinate reference system) for the map render.
void readXml(QDomNode &node)
QgsRectangle computeExtentForScale(const QgsPointXY &center, double scale) const
Compute the extent such that its center is at the specified position (mapped to the destinatonCrs) an...
void setMagnificationFactor(double factor, const QgsPointXY *center=nullptr)
Set the magnification factor.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which stores various information regarding which datum tran...
Perform transforms between map coordinates and device coordinates.
Definition: qgsmaptopixel.h:39
QgsPointXY toMapCoordinates(int x, int y) const
Transforms device coordinates to map (world) coordinates.
void setParameters(double mapUnitsPerPixel, double centerX, double centerY, int widthPixels, int heightPixels, double rotation)
Sets parameters for use in transforming coordinates.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true)
Adds a message to the log instance (and creates it if necessary).
A class to represent a 2D point.
Definition: qgspointxy.h:59
double y
Definition: qgspointxy.h:63
Q_GADGET double x
Definition: qgspointxy.h:62
QPointF toQPointF() const
Converts a point to a QPointF.
Definition: qgspointxy.h:169
Point geometry type, with support for z-dimension and m-values.
Definition: qgspoint.h:49
Q_GADGET double x
Definition: qgspoint.h:52
double z
Definition: qgspoint.h:54
double m
Definition: qgspoint.h:55
double y
Definition: qgspoint.h:53
A rectangle specified with double values.
Definition: qgsrectangle.h:42
QString toString(int precision=16) const
Returns a string representation of form xmin,ymin : xmax,ymax Coordinates will be truncated to the sp...
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
Definition: qgsrectangle.h:256
double yMaximum() const SIP_HOLDGIL
Returns the y maximum value (top side of rectangle).
Definition: qgsrectangle.h:193
double xMaximum() const SIP_HOLDGIL
Returns the x maximum value (right side of rectangle).
Definition: qgsrectangle.h:183
double xMinimum() const SIP_HOLDGIL
Returns the x minimum value (left side of rectangle).
Definition: qgsrectangle.h:188
double yMinimum() const SIP_HOLDGIL
Returns the y minimum value (bottom side of rectangle).
Definition: qgsrectangle.h:198
QString asWktCoordinates() const
Returns a string representation of the rectangle in WKT format.
double height() const SIP_HOLDGIL
Returns the height of the rectangle.
Definition: qgsrectangle.h:230
void set(const QgsPointXY &p1, const QgsPointXY &p2, bool normalize=true)
Sets the rectangle from two QgsPoints.
Definition: qgsrectangle.h:122
void setMinimal() SIP_HOLDGIL
Set a rectangle so that min corner is at max and max corner is at min.
Definition: qgsrectangle.h:172
double width() const SIP_HOLDGIL
Returns the width of the rectangle.
Definition: qgsrectangle.h:223
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
Definition: qgsrectangle.h:391
bool isEmpty() const
Returns true if the rectangle is empty.
Definition: qgsrectangle.h:469
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Definition: qgsrectangle.h:559
QgsPointXY center() const SIP_HOLDGIL
Returns the center point of the rectangle.
Definition: qgsrectangle.h:251
An interface for classes which provider custom handlers for features rendered as part of a map render...
double calculate(const QgsRectangle &mapExtent, double canvasWidth) const
Calculate the scale denominator.
void setDpi(double dpi)
Sets the dpi (dots per inch) for the output resolution, to be used in scale calculations.
void setMapUnits(Qgis::DistanceUnit mapUnits)
Set the map units.
Qgis::DistanceUnit mapUnits() const
Returns current map units.
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
void setSimplifyHints(SimplifyHints simplifyHints)
Sets the simplification hints of the vector layer managed.
@ NoSimplification
No simplification can be applied.
static QDomElement writeRectangle(const QgsRectangle &rect, QDomDocument &doc, const QString &elementName=QStringLiteral("extent"))
Encodes a rectangle to a DOM element.
Definition: qgsxmlutils.cpp:81
static QgsRectangle readRectangle(const QDomElement &element)
Definition: qgsxmlutils.cpp:39
static QDomElement writeMapUnits(Qgis::DistanceUnit units, QDomDocument &doc)
Encodes a distance unit to a DOM element.
Definition: qgsxmlutils.cpp:69
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition: qgis.h:3448
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition: qgis.h:3509
#define QgsDebugMsgLevel(str, level)
Definition: qgslogger.h:39
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
Definition: qgsmaplayer.h:2206
Q_GUI_EXPORT int qt_defaultDpiX()
const QgsCoordinateReferenceSystem & crs
Contains parameters for an ellipsoid.
bool valid
Whether ellipsoid parameters are valid.