QGIS API Documentation 3.99.0-Master (d270888f95f)
Loading...
Searching...
No Matches
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
19#include "qgsellipsoidutils.h"
20#include "qgsexception.h"
21#include "qgsgeometry.h"
22#include "qgsgrouplayer.h"
23#include "qgslogger.h"
24#include "qgsmaplayer.h"
26#include "qgsmaptopixel.h"
27#include "qgsmessagelog.h"
28#include "qgspainting.h"
29#include "qgsscalecalculator.h"
30#include "qgsunittypes.h"
31#include "qgsxmlutils.h"
32
33#include <QString>
34
35using namespace Qt::StringLiterals;
36
38 : mDpi( QgsPainting::qtDefaultDpiX() ) // DPI that will be used by default for QImage instances
39 , mSize( QSize( 0, 0 ) )
40 , mBackgroundColor( Qt::white )
41 , mSelectionColor( Qt::yellow )
42 , mFlags( Qgis::MapSettingsFlag::Antialiasing | Qgis::MapSettingsFlag::UseAdvancedEffects | Qgis::MapSettingsFlag::DrawLabeling | Qgis::MapSettingsFlag::DrawSelection )
43 , mSegmentationTolerance( M_PI_2 / 90 )
44{
47
49}
50
51void QgsMapSettings::setMagnificationFactor( double factor, const QgsPointXY *center )
52{
53 const double ratio = mMagnificationFactor / factor;
54
55 mMagnificationFactor = factor;
56
57 const double rot = rotation();
58 setRotation( 0.0 );
59
61 ext.scale( ratio, center );
62
63 mRotation = rot;
64 mExtent = ext;
65 mDpi = mDpi / ratio;
66
67 QgsDebugMsgLevel( u"Magnification factor: %1 dpi: %2 ratio: %3"_s.arg( factor ).arg( mDpi ).arg( ratio ), 3 );
68
70}
71
76
78{
79 return mExtent;
80}
81
82void QgsMapSettings::setExtent( const QgsRectangle &extent, bool magnified )
83{
84 QgsRectangle magnifiedExtent = extent;
85
86 if ( !magnified )
87 magnifiedExtent.scale( 1 / mMagnificationFactor );
88
89 mExtent = magnifiedExtent;
90
92}
93
95{
96 return mExtentBuffer;
97}
98
99void QgsMapSettings::setExtentBuffer( const double buffer )
100{
101 mExtentBuffer = buffer;
102}
103
105{
106 return mRotation;
107}
108
109void QgsMapSettings::setRotation( double degrees )
110{
111 if ( qgsDoubleNear( mRotation, degrees ) )
112 return;
113
114 mRotation = degrees;
115
116 // TODO: update extent while keeping scale ?
118}
119
120
122{
124
125 if ( extent.isEmpty() || !extent.isFinite() )
126 {
127 mValid = false;
128 return;
129 }
130
131 // Don't allow zooms where the current extent is so small that it
132 // can't be accurately represented using a double (which is what
133 // currentExtent uses). Excluding 0 avoids a divide by zero and an
134 // infinite loop when rendering to a new canvas. Excluding extents
135 // greater than 1 avoids doing unnecessary calculations.
136
137 // The scheme is to compare the width against the mean x coordinate
138 // (and height against mean y coordinate) and only allow zooms where
139 // the ratio indicates that there is more than about 12 significant
140 // figures (there are about 16 significant figures in a double).
141
142 if ( extent.width() > 0 &&
143 extent.height() > 0 &&
144 extent.width() < 1 &&
145 extent.height() < 1 )
146 {
147 // Use abs() on the extent to avoid the case where the extent is
148 // symmetrical about 0.
149 const double xMean = ( std::fabs( extent.xMinimum() ) + std::fabs( extent.xMaximum() ) ) * 0.5;
150 const double yMean = ( std::fabs( extent.yMinimum() ) + std::fabs( extent.yMaximum() ) ) * 0.5;
151
152 const double xRange = extent.width() / xMean;
153 const double yRange = extent.height() / yMean;
154
155 static const double MIN_PROPORTION = 1e-12;
156 if ( xRange < MIN_PROPORTION || yRange < MIN_PROPORTION )
157 {
158 mValid = false;
159 return;
160 }
161 }
162
163 const double myHeight = mSize.height();
164 const double myWidth = mSize.width();
165
166 if ( !myWidth || !myHeight )
167 {
168 mValid = false;
169 return;
170 }
171
172 // calculate the translation and scaling parameters
173 const double mapUnitsPerPixelY = mExtent.height() / myHeight;
174 const double mapUnitsPerPixelX = mExtent.width() / myWidth;
175 mMapUnitsPerPixel = mapUnitsPerPixelY > mapUnitsPerPixelX ? mapUnitsPerPixelY : mapUnitsPerPixelX;
176
177 // calculate the actual extent of the mapCanvas
178 double dxmin = mExtent.xMinimum(), dxmax = mExtent.xMaximum(),
179 dymin = mExtent.yMinimum(), dymax = mExtent.yMaximum(), whitespace;
180
181 if ( mapUnitsPerPixelY > mapUnitsPerPixelX )
182 {
183 whitespace = ( ( myWidth * mMapUnitsPerPixel ) - mExtent.width() ) * 0.5;
184 dxmin -= whitespace;
185 dxmax += whitespace;
186 }
187 else
188 {
189 whitespace = ( ( myHeight * mMapUnitsPerPixel ) - mExtent.height() ) * 0.5;
190 dymin -= whitespace;
191 dymax += whitespace;
192 }
193
194 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
195
196 // update the scale
197 mScaleCalculator.setDpi( mDpi );
198 mScale = mScaleCalculator.calculate( mVisibleExtent, mSize.width() );
199
200 bool ok = true;
201 mMapToPixel.setParameters(
203 visibleExtent().center().x(),
204 visibleExtent().center().y(),
205 outputSize().width(),
206 outputSize().height(),
207 mRotation, &ok );
208
209 mValid = ok;
210
211#if 1 // set visible extent taking rotation in consideration
212 if ( mRotation )
213 {
214 const QgsPointXY p1 = mMapToPixel.toMapCoordinates( QPoint( 0, 0 ) );
215 const QgsPointXY p2 = mMapToPixel.toMapCoordinates( QPoint( 0, myHeight ) );
216 const QgsPointXY p3 = mMapToPixel.toMapCoordinates( QPoint( myWidth, 0 ) );
217 const QgsPointXY p4 = mMapToPixel.toMapCoordinates( QPoint( myWidth, myHeight ) );
218 dxmin = std::min( p1.x(), std::min( p2.x(), std::min( p3.x(), p4.x() ) ) );
219 dymin = std::min( p1.y(), std::min( p2.y(), std::min( p3.y(), p4.y() ) ) );
220 dxmax = std::max( p1.x(), std::max( p2.x(), std::max( p3.x(), p4.x() ) ) );
221 dymax = std::max( p1.y(), std::max( p2.y(), std::max( p3.y(), p4.y() ) ) );
222 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
223 }
224#endif
225
226 QgsDebugMsgLevel( u"Map units per pixel (x,y) : %1, %2"_s.arg( qgsDoubleToString( mapUnitsPerPixelX ), qgsDoubleToString( mapUnitsPerPixelY ) ), 5 );
227 QgsDebugMsgLevel( u"Pixmap dimensions (x,y) : %1, %2"_s.arg( qgsDoubleToString( mSize.width() ), qgsDoubleToString( mSize.height() ) ), 5 );
228 QgsDebugMsgLevel( u"Extent dimensions (x,y) : %1, %2"_s.arg( qgsDoubleToString( mExtent.width() ), qgsDoubleToString( mExtent.height() ) ), 5 );
229 QgsDebugMsgLevel( mExtent.toString(), 5 );
230 QgsDebugMsgLevel( u"Adjusted map units per pixel (x,y) : %1, %2"_s.arg( qgsDoubleToString( mVisibleExtent.width() / myWidth ), qgsDoubleToString( mVisibleExtent.height() / myHeight ) ), 5 );
231 QgsDebugMsgLevel( u"Recalced pixmap dimensions (x,y) : %1, %2"_s.arg( qgsDoubleToString( mVisibleExtent.width() / mMapUnitsPerPixel ), qgsDoubleToString( mVisibleExtent.height() / mMapUnitsPerPixel ) ), 5 );
232 QgsDebugMsgLevel( u"Scale (assuming meters as map units) = 1:%1"_s.arg( qgsDoubleToString( mScale ) ), 5 );
233 QgsDebugMsgLevel( u"Rotation: %1 degrees"_s.arg( mRotation ), 5 );
234 QgsDebugMsgLevel( u"Extent: %1"_s.arg( mExtent.asWktCoordinates() ), 5 );
235 QgsDebugMsgLevel( u"Visible Extent: %1"_s.arg( mVisibleExtent.asWktCoordinates() ), 5 );
236 QgsDebugMsgLevel( u"Magnification factor: %1"_s.arg( mMagnificationFactor ), 5 );
237
238}
239
240void QgsMapSettings::matchRasterizedRenderingPolicyToFlags()
241{
251}
252
254{
255 return mSize;
256}
257
259{
260 mSize = size;
261
263}
264
266{
267 return mDevicePixelRatio;
268}
269
271{
272 mDevicePixelRatio = dpr;
274}
275
277{
278 return outputSize() * mDevicePixelRatio;
279}
280
282{
283 return mDpi;
284}
285
287{
288 mDpi = dpi;
289
291}
292
294{
295 return mDpiTarget;
296}
297
299{
300 mDpiTarget = dpi;
301}
302
303QStringList QgsMapSettings::layerIds( bool expandGroupLayers ) const
304{
305 if ( !expandGroupLayers || !mHasGroupLayers )
306 {
307 return mLayerIds;
308 }
309 else
310 {
311 const QList<QgsMapLayer * > mapLayers = layers( expandGroupLayers );
312 QStringList res;
313 res.reserve( mapLayers.size() );
314 for ( const QgsMapLayer *layer : mapLayers )
315 res << layer->id();
316 return res;
317 }
318}
319
320QList<QgsMapLayer *> QgsMapSettings::layers( bool expandGroupLayers ) const
321{
322 const QList<QgsMapLayer *> actualLayers = _qgis_listQPointerToRaw( mLayers );
323 if ( !expandGroupLayers )
324 return actualLayers;
325
326 QList< QgsMapLayer * > result;
327
328 std::function< void( const QList< QgsMapLayer * >& layers ) > expandLayers;
329 expandLayers = [&result, &expandLayers]( const QList< QgsMapLayer * > &layers )
330 {
331 for ( QgsMapLayer *layer : layers )
332 {
333 if ( QgsGroupLayer *groupLayer = qobject_cast< QgsGroupLayer * >( layer ) )
334 {
335 expandLayers( groupLayer->childLayers() );
336 }
337 else
338 {
339 result << layer;
340 }
341 }
342 };
343
344 expandLayers( actualLayers );
345 return result;
346}
347
348template<typename T>
349QVector<T> QgsMapSettings::layers() const
350{
351 const QList<QgsMapLayer *> actualLayers = _qgis_listQPointerToRaw( mLayers );
352
353 QVector<T> layers;
354 for ( QgsMapLayer *layer : actualLayers )
355 {
356 T tLayer = qobject_cast<T>( layer );
357 if ( tLayer )
358 {
359 layers << tLayer;
360 }
361 }
362 return layers;
363}
364
365void QgsMapSettings::setLayers( const QList<QgsMapLayer *> &layers )
366{
367 // filter list, removing null layers and non-spatial layers
368 auto filteredList = layers;
369 filteredList.erase( std::remove_if( filteredList.begin(), filteredList.end(),
370 []( QgsMapLayer * layer )
371 {
372 return !layer || !layer->isSpatial();
373 } ), filteredList.end() );
374
375 mLayers = _qgis_listRawToQPointer( filteredList );
376
377 // pre-generate and store layer IDs, so that we can safely access them from other threads
378 // without needing to touch the actual map layer object
379 mLayerIds.clear();
380 mHasGroupLayers = false;
381 mLayerIds.reserve( mLayers.size() );
382 for ( const QgsMapLayer *layer : std::as_const( mLayers ) )
383 {
384 mLayerIds << layer->id();
385 if ( layer->type() == Qgis::LayerType::Group )
386 mHasGroupLayers = true;
387 }
388}
389
390QMap<QString, QString> QgsMapSettings::layerStyleOverrides() const
391{
393}
394
395void QgsMapSettings::setLayerStyleOverrides( const QMap<QString, QString> &overrides )
396{
397 mLayerStyleOverrides = overrides;
398}
399
401{
402 mDestCRS = crs;
403 mScaleCalculator.setMapUnits( crs.mapUnits() );
404 // Since the map units have changed, force a recalculation of the scale.
406}
407
412
414{
416 if ( !params.valid )
417 {
418 return false;
419 }
420 else
421 {
423 return true;
424 }
425}
426
428{
429 mFlags = flags;
430 matchRasterizedRenderingPolicyToFlags();
431}
432
434{
435 if ( on )
436 mFlags |= flag;
437 else
438 mFlags &= ~( static_cast< int >( flag ) );
439 matchRasterizedRenderingPolicyToFlags();
440}
441
446
448{
449 return mFlags.testFlag( flag );
450}
451
453{
454 return mScaleCalculator.mapUnits();
455}
456
461
463{
464 mScaleCalculator.setMethod( method );
466}
467
469{
470 return mValid;
471}
472
477
479{
480 QPolygonF poly;
481
482 const QSize &sz = outputSize();
483 const QgsMapToPixel &m2p = mapToPixel();
484
485 poly << m2p.toMapCoordinates( 0.0, 0.0 ).toQPointF();
486 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), 0.0 ).toQPointF();
487 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), static_cast<double>( sz.height() ) ).toQPointF();
488 poly << m2p.toMapCoordinates( 0.0, static_cast<double>( sz.height() ) ).toQPointF();
489
490 return poly;
491}
492
494{
495 QPolygonF poly;
496
497 const QSize &sz = outputSize();
498 const QgsMapToPixel &m2p = mapToPixel();
499
500 // Transform tilebuffer in pixel.
501 // Original tilebuffer is in pixel and transformed only according
502 // extent width (see QgsWmsRenderContext::mapTileBuffer)
503
504 const double mapUnitsPerPixel = mExtent.width() / sz.width();
505 const double buffer = mExtentBuffer / mapUnitsPerPixel;
506
507 poly << m2p.toMapCoordinates( -buffer, -buffer ).toQPointF();
508 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), -buffer ).toQPointF();
509 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), static_cast<double>( sz.height() + buffer ) ).toQPointF();
510 poly << m2p.toMapCoordinates( -buffer, static_cast<double>( sz.height() + buffer ) ).toQPointF();
511
512 return poly;
513}
514
516{
517 return mMapUnitsPerPixel;
518}
519
521{
522 return mScale;
523}
524
526{
527#ifdef QGISDEBUG
528 if ( !mHasTransformContext )
529 QgsDebugMsgLevel( u"No QgsCoordinateTransformContext context set for transform"_s, 4 );
530#endif
531
532 return mTransformContext;
533}
534
536{
537 mTransformContext = context;
538#ifdef QGISDEBUG
539 mHasTransformContext = true;
540#endif
541}
542
544{
545 if ( !layer )
546 return QgsCoordinateTransform();
547
549}
550
552{
553 // Output width in inches
554 const double outputWidthInInches = outputSize().width() / outputDpi();
555
556 // Desired visible width (honouring scale)
557 const double scaledWidthInInches = outputWidthInInches * scale;
558
560 {
561 // Start with some fraction of the current extent around the center
562 const double delta = mExtent.width() / 100.;
563 QgsRectangle ext( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
564 // Get scale at extent, and then scale extent to the desired scale
565 const double testScale = mScaleCalculator.calculate( ext, outputSize().width() );
566 ext.scale( scale / testScale );
567 return ext;
568 }
569 else
570 {
571 // Conversion from inches to mapUnits - this is safe to use, because we know here that the map units AREN'T in degrees
572 const double conversionFactor = QgsUnitTypes::fromUnitToUnitFactor( Qgis::DistanceUnit::Feet, mapUnits() ) / 12;
573
574 const double delta = 0.5 * scaledWidthInInches * conversionFactor;
575 return QgsRectangle( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
576 }
577}
578
580{
581 return mScaleCalculator.calculate( extent, outputSize().width() );
582}
583
584double QgsMapSettings::layerToMapUnits( const QgsMapLayer *layer, const QgsRectangle &referenceExtent ) const
585{
586 return layerTransform( layer ).scaleFactor( referenceExtent );
587}
588
589
591{
592 try
593 {
595 if ( ct.isValid() )
596 {
597 QgsDebugMsgLevel( u"sourceCrs = %1"_s.arg( ct.sourceCrs().authid() ), 3 );
598 QgsDebugMsgLevel( u"destCRS = %1"_s.arg( ct.destinationCrs().authid() ), 3 );
599 QgsDebugMsgLevel( u"extent %1"_s.arg( extent.toString() ), 3 );
602 }
603 }
604 catch ( QgsCsException &cse )
605 {
606 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
607 }
608
609 QgsDebugMsgLevel( u"proj extent = %1 "_s.arg( extent.toString() ), 3 );
610
611 return extent;
612}
613
614
616{
617 try
618 {
621 if ( ct.isValid() )
622 {
623 QgsDebugMsgLevel( u"sourceCrs = %1"_s.arg( ct.sourceCrs().authid() ), 3 );
624 QgsDebugMsgLevel( u"destCRS = %1"_s.arg( ct.destinationCrs().authid() ), 3 );
625 QgsDebugMsgLevel( u"extent = %1"_s.arg( extent.toString() ), 3 );
627 }
628 }
629 catch ( QgsCsException &cse )
630 {
631 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
632 }
633
634 QgsDebugMsgLevel( u"proj extent = %1"_s.arg( extent.toString() ), 3 );
635
636 return extent;
637}
638
639
641{
642 try
643 {
644 const QgsCoordinateTransform ct = layerTransform( layer );
645 if ( ct.isValid() )
646 point = ct.transform( point, Qgis::TransformDirection::Forward );
647 }
648 catch ( QgsCsException &cse )
649 {
650 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
651 }
652
653 return point;
654}
655
657{
658 double x = point.x();
659 double y = point.y();
660 double z = point.z();
661 const double m = point.m();
662
663 try
664 {
665 const QgsCoordinateTransform ct = layerTransform( layer );
666 if ( ct.isValid() )
668 }
669 catch ( QgsCsException &cse )
670 {
671 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
672 }
673
674 return QgsPoint( x, y, z, m );
675}
676
677
679{
680 try
681 {
682 const QgsCoordinateTransform ct = layerTransform( layer );
683 if ( ct.isValid() )
685 }
686 catch ( QgsCsException &cse )
687 {
688 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
689 }
690
691 return rect;
692}
693
694
696{
697 try
698 {
699 const QgsCoordinateTransform ct = layerTransform( layer );
700 if ( ct.isValid() )
701 point = ct.transform( point, Qgis::TransformDirection::Reverse );
702 }
703 catch ( QgsCsException &cse )
704 {
705 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
706 }
707
708 return point;
709}
710
712{
713 double x = point.x();
714 double y = point.y();
715 double z = point.z();
716 const double m = point.m();
717
718 try
719 {
720 const QgsCoordinateTransform ct = layerTransform( layer );
721 if ( ct.isValid() )
723 }
724 catch ( QgsCsException &cse )
725 {
726 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
727 }
728
729 return QgsPoint( x, y, z, m );
730}
731
732
734{
735 try
736 {
737 const QgsCoordinateTransform ct = layerTransform( layer );
738 if ( ct.isValid() )
740 }
741 catch ( QgsCsException &cse )
742 {
743 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
744 }
745
746 return rect;
747}
748
749
750
752{
753 // reset the map canvas extent since the extent may now be smaller
754 // We can't use a constructor since QgsRectangle normalizes the rectangle upon construction
756 fullExtent.setNull();
757
758 // iterate through the map layers and test each layers extent
759 // against the current min and max values
760 QgsDebugMsgLevel( u"Layer count: %1"_s.arg( mLayers.count() ), 5 );
761 const auto constMLayers = mLayers;
762 for ( const QgsWeakMapLayerPointer &layerPtr : constMLayers )
763 {
764 if ( QgsMapLayer *lyr = layerPtr.data() )
765 {
766 QgsDebugMsgLevel( "Updating extent using " + lyr->name(), 5 );
767 QgsDebugMsgLevel( "Input extent: " + lyr->extent().toString(), 5 );
768
769 if ( lyr->extent().isNull() )
770 continue;
771
772 // Layer extents are stored in the coordinate system (CS) of the
773 // layer. The extent must be projected to the canvas CS
774 const QgsRectangle extent = layerExtentToOutputExtent( lyr, lyr->extent() );
775
776 QgsDebugMsgLevel( "Output extent: " + extent.toString(), 5 );
777 fullExtent.combineExtentWith( extent );
778 }
779 }
780
781 if ( fullExtent.width() == 0.0 || fullExtent.height() == 0.0 )
782 {
783 // If all of the features are at the one point, buffer the
784 // rectangle a bit. If they are all at zero, do something a bit
785 // more crude.
786
787 if ( fullExtent.xMinimum() == 0.0 && fullExtent.xMaximum() == 0.0 &&
788 fullExtent.yMinimum() == 0.0 && fullExtent.yMaximum() == 0.0 )
789 {
790 fullExtent.set( -1.0, -1.0, 1.0, 1.0 );
791 }
792 else
793 {
794 const double padFactor = 1e-8;
795 const double widthPad = fullExtent.xMinimum() * padFactor;
796 const double heightPad = fullExtent.yMinimum() * padFactor;
797 const double xmin = fullExtent.xMinimum() - widthPad;
798 const double xmax = fullExtent.xMaximum() + widthPad;
799 const double ymin = fullExtent.yMinimum() - heightPad;
800 const double ymax = fullExtent.yMaximum() + heightPad;
801 fullExtent.set( xmin, ymin, xmax, ymax );
802 }
803 }
804
805 QgsDebugMsgLevel( "Full extent: " + fullExtent.toString(), 5 );
806 return fullExtent;
807}
808
809
810void QgsMapSettings::readXml( QDomNode &node )
811{
812 // set destination CRS
814 const QDomNode srsNode = node.namedItem( u"destinationsrs"_s );
815 if ( !srsNode.isNull() )
816 {
817 srs.readXml( srsNode );
818 }
819 setDestinationCrs( srs );
820
821 // set extent
822 const QDomNode extentNode = node.namedItem( u"extent"_s );
823 const QgsRectangle aoi = QgsXmlUtils::readRectangle( extentNode.toElement() );
824 setExtent( aoi );
825
826 // set rotation
827 const QDomNode rotationNode = node.namedItem( u"rotation"_s );
828 const QString rotationVal = rotationNode.toElement().text();
829 if ( ! rotationVal.isEmpty() )
830 {
831 const double rot = rotationVal.toDouble();
832 setRotation( rot );
833 }
834
835 //render map tile
836 const QDomElement renderMapTileElem = node.firstChildElement( u"rendermaptile"_s );
837 if ( !renderMapTileElem.isNull() )
838 {
839 setFlag( Qgis::MapSettingsFlag::RenderMapTile, renderMapTileElem.text() == "1"_L1 );
840 }
841}
842
843
844
845void QgsMapSettings::writeXml( QDomNode &node, QDomDocument &doc )
846{
847 // units
848 node.appendChild( QgsXmlUtils::writeMapUnits( mapUnits(), doc ) );
849
850 // Write current view extents
851 node.appendChild( QgsXmlUtils::writeRectangle( extent(), doc ) );
852
853 // Write current view rotation
854 QDomElement rotNode = doc.createElement( u"rotation"_s );
855 rotNode.appendChild(
856 doc.createTextNode( qgsDoubleToString( rotation() ) )
857 );
858 node.appendChild( rotNode );
859
860 // destination CRS
861 if ( mDestCRS.isValid() )
862 {
863 QDomElement srsNode = doc.createElement( u"destinationsrs"_s );
864 node.appendChild( srsNode );
865 mDestCRS.writeXml( srsNode, doc );
866 }
867
868 //render map tile
869 QDomElement renderMapTileElem = doc.createElement( u"rendermaptile"_s );
870 const QDomText renderMapTileText = doc.createTextNode( testFlag( Qgis::MapSettingsFlag::RenderMapTile ) ? "1" : "0" );
871 renderMapTileElem.appendChild( renderMapTileText );
872 node.appendChild( renderMapTileElem );
873}
874
879
881{
882 mLabelBoundaryGeometry = boundary;
883}
884
886{
887 mClippingRegions.append( region );
888}
889
890void QgsMapSettings::setClippingRegions( const QList<QgsMapClippingRegion> &regions )
891{
892 mClippingRegions = regions;
893}
894
895QList<QgsMapClippingRegion> QgsMapSettings::clippingRegions() const
896{
897 return mClippingRegions;
898}
899
901{
902 mMaskRenderSettings = settings;
903}
904
906{
907 mRenderedFeatureHandlers.append( handler );
908}
909
910QList<QgsRenderedFeatureHandlerInterface *> QgsMapSettings::renderedFeatureHandlers() const
911{
912 return mRenderedFeatureHandlers;
913}
914
916{
917 return mZRange;
918}
919
921{
922 mZRange = zRange;
923}
924
929
934
936{
937 return mFrameRate;
938}
939
941{
942 mFrameRate = rate;
943}
944
946{
947 return mCurrentFrame;
948}
949
950void QgsMapSettings::setCurrentFrame( long long frame )
951{
952 mCurrentFrame = frame;
953}
954
959
964
969
989
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:59
RasterizedRenderingPolicy
Policies controlling when rasterisation of content during renders is permitted.
Definition qgis.h:2761
@ Default
Allow raster-based rendering in situations where it is required for correct rendering or where it wil...
Definition qgis.h:2762
@ PreferVector
Prefer vector-based rendering, when the result will still be visually near-identical to a raster-base...
Definition qgis.h:2763
@ ForceVector
Always force vector-based rendering, even when the result will be visually different to a raster-base...
Definition qgis.h:2764
QFlags< MapSettingsFlag > MapSettingsFlags
Map settings flags.
Definition qgis.h:2796
@ NoSimplification
No simplification can be applied.
Definition qgis.h:3088
DistanceUnit
Units of distance.
Definition qgis.h:5085
@ Feet
Imperial feet.
Definition qgis.h:5088
@ Unknown
Unknown distance unit.
Definition qgis.h:5135
@ Degrees
Degrees, for planar geographic CRS distance measurements.
Definition qgis.h:5092
@ Group
Composite group layer. Added in QGIS 3.24.
Definition qgis.h:201
ScaleCalculationMethod
Scale calculation logic.
Definition qgis.h:5357
RendererUsage
Usage of the renderer.
Definition qgis.h:3504
@ Forward
Forward transform (from source to destination).
Definition qgis.h:2730
@ Reverse
Reverse/inverse transform (from destination to source).
Definition qgis.h:2731
MapSettingsFlag
Flags which adjust the way maps are rendered.
Definition qgis.h:2774
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
Definition qgis.h:2783
@ ForceVectorOutput
Vector graphics should not be cached and drawn as raster images.
Definition qgis.h:2777
@ UseAdvancedEffects
Enable layer opacity and blending effects.
Definition qgis.h:2778
Represents a coordinate reference system (CRS).
bool readXml(const QDomNode &node)
Restores state from the given DOM node.
Contains information about the context in which a coordinate transform is executed.
Handles coordinate transforms between two 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:
QgsPointXY transform(const QgsPointXY &point, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transform the point from the source CRS to the destination CRS.
void transformInPlace(double &x, double &y, double &z, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward) const
Transforms an array of x, y and z double coordinates in place, from the source CRS to the destination...
QgsRectangle transformBoundingBox(const QgsRectangle &rectangle, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool handle180Crossover=false) const
Transforms a rectangle from the source CRS to the destination CRS.
bool isValid() const
Returns true if the coordinate transform is valid, ie both the source and destination CRS have been s...
QgsCoordinateReferenceSystem destinationCrs() const
Returns the destination coordinate reference system, which the transform will transform coordinates t...
Custom exception class for Coordinate Reference System related exceptions.
QgsRange which stores a range of double values.
Definition qgsrange.h:236
Renders elevation shading on an image with different methods (eye dome lighting, hillshading,...
static EllipsoidParameters ellipsoidParameters(const QString &ellipsoid)
Returns the parameters for the specified ellipsoid.
QString what() const
A geometry is the spatial representation of a feature.
A map layer which consists of a set of child layers, where all component layers are rendered as a sin...
A map clipping region (in map coordinates and CRS).
Base class for all map layer types.
Definition qgsmaplayer.h:83
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:90
QString id
Definition qgsmaplayer.h:86
Qgis::LayerType type
Definition qgsmaplayer.h:93
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)
Writes the map settings to an XML node.
QgsPointXY layerToMapCoordinates(const QgsMapLayer *layer, QgsPointXY point) const
transform point coordinates from layer's CRS to output CRS
QgsMaskRenderSettings mMaskRenderSettings
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 setScaleMethod(Qgis::ScaleCalculationMethod method)
Sets the method to use for scale calculations for the map.
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.
QStringList mLayerIds
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.
void setRasterizedRenderingPolicy(Qgis::RasterizedRenderingPolicy policy)
Sets the policy controlling when rasterisation of content during renders is permitted.
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.
void setMaskSettings(const QgsMaskRenderSettings &settings)
Sets the mask render settings, which control how masks are drawn and behave during the map render.
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, where layerUnits × layerToMapUni...
double extentBuffer() const
Returns the buffer in map units to use around the visible extent for rendering symbols whose correspo...
QVector< T > layers() const
Returns a list of registered map layers with a specified layer type.
QgsScaleCalculator mScaleCalculator
Qgis::MapSettingsFlags flags() const
Returns combination of flags used for rendering.
Qgis::ScaleCalculationMethod scaleMethod() const
Returns the method to use for scale calculations for the map.
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...
Qgis::RasterizedRenderingPolicy mRasterizedRenderingPolicy
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.
Qgis::RasterizedRenderingPolicy rasterizedRenderingPolicy() const
Returns the policy controlling when rasterisation of content during renders is permitted.
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)
Restore the map settings from a XML node.
double mSegmentationTolerance
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.
QgsPointXY toMapCoordinates(int x, int y) const
Transforms device coordinates to map (world) coordinates.
Contains settings regarding how masks are calculated and handled during a map render.
static void logMessage(const QString &message, const QString &tag=QString(), Qgis::MessageLevel level=Qgis::MessageLevel::Warning, bool notifyUser=true, const char *file=__builtin_FILE(), const char *function=__builtin_FUNCTION(), int line=__builtin_LINE())
Adds a message to the log instance (and creates it if necessary).
Contains miscellaneous painting utility functions.
Definition qgspainting.h:32
Represents a 2D point.
Definition qgspointxy.h:62
double y
Definition qgspointxy.h:66
double x
Definition qgspointxy.h:65
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:167
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:53
double z
Definition qgspoint.h:58
double x
Definition qgspoint.h:56
double m
Definition qgspoint.h:59
double y
Definition qgspoint.h:57
A rectangle specified with double values.
void scale(double scaleFactor, const QgsPointXY *c=nullptr)
Scale the rectangle around its center point.
An interface for classes which provide custom handlers for features rendered as part of a map render ...
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
static QDomElement writeRectangle(const QgsRectangle &rect, QDomDocument &doc, const QString &elementName=u"extent"_s)
Encodes a rectangle to a DOM element.
static QgsRectangle readRectangle(const QDomElement &element)
static QDomElement writeMapUnits(Qgis::DistanceUnit units, QDomDocument &doc)
Encodes a distance unit to a DOM element.
QString qgsDoubleToString(double a, int precision=17)
Returns a string representation of a double.
Definition qgis.h:6817
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference).
Definition qgis.h:6900
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
Contains parameters for an ellipsoid.
bool valid
Whether ellipsoid parameters are valid.