QGIS API Documentation 3.43.0-Master (b60ef06885e)
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#include "qgspainting.h"
33
35 : mDpi( QgsPainting::qtDefaultDpiX() ) // DPI that will be used by default for QImage instances
36 , mSize( QSize( 0, 0 ) )
37 , mBackgroundColor( Qt::white )
38 , mSelectionColor( Qt::yellow )
39 , mFlags( Qgis::MapSettingsFlag::Antialiasing | Qgis::MapSettingsFlag::UseAdvancedEffects | Qgis::MapSettingsFlag::DrawLabeling | Qgis::MapSettingsFlag::DrawSelection )
40 , mSegmentationTolerance( M_PI_2 / 90 )
41{
44
46}
47
48void QgsMapSettings::setMagnificationFactor( double factor, const QgsPointXY *center )
49{
50 const double ratio = mMagnificationFactor / factor;
51
52 mMagnificationFactor = factor;
53
54 const double rot = rotation();
55 setRotation( 0.0 );
56
58 ext.scale( ratio, center );
59
60 mRotation = rot;
61 mExtent = ext;
62 mDpi = mDpi / ratio;
63
64 QgsDebugMsgLevel( QStringLiteral( "Magnification factor: %1 dpi: %2 ratio: %3" ).arg( factor ).arg( mDpi ).arg( ratio ), 3 );
65
67}
68
73
75{
76 return mExtent;
77}
78
79void QgsMapSettings::setExtent( const QgsRectangle &extent, bool magnified )
80{
81 QgsRectangle magnifiedExtent = extent;
82
83 if ( !magnified )
84 magnifiedExtent.scale( 1 / mMagnificationFactor );
85
86 mExtent = magnifiedExtent;
87
89}
90
92{
93 return mExtentBuffer;
94}
95
96void QgsMapSettings::setExtentBuffer( const double buffer )
97{
98 mExtentBuffer = buffer;
99}
100
102{
103 return mRotation;
104}
105
106void QgsMapSettings::setRotation( double degrees )
107{
108 if ( qgsDoubleNear( mRotation, degrees ) )
109 return;
110
111 mRotation = degrees;
112
113 // TODO: update extent while keeping scale ?
115}
116
117
119{
121
122 if ( extent.isEmpty() || !extent.isFinite() )
123 {
124 mValid = false;
125 return;
126 }
127
128 // Don't allow zooms where the current extent is so small that it
129 // can't be accurately represented using a double (which is what
130 // currentExtent uses). Excluding 0 avoids a divide by zero and an
131 // infinite loop when rendering to a new canvas. Excluding extents
132 // greater than 1 avoids doing unnecessary calculations.
133
134 // The scheme is to compare the width against the mean x coordinate
135 // (and height against mean y coordinate) and only allow zooms where
136 // the ratio indicates that there is more than about 12 significant
137 // figures (there are about 16 significant figures in a double).
138
139 if ( extent.width() > 0 &&
140 extent.height() > 0 &&
141 extent.width() < 1 &&
142 extent.height() < 1 )
143 {
144 // Use abs() on the extent to avoid the case where the extent is
145 // symmetrical about 0.
146 const double xMean = ( std::fabs( extent.xMinimum() ) + std::fabs( extent.xMaximum() ) ) * 0.5;
147 const double yMean = ( std::fabs( extent.yMinimum() ) + std::fabs( extent.yMaximum() ) ) * 0.5;
148
149 const double xRange = extent.width() / xMean;
150 const double yRange = extent.height() / yMean;
151
152 static const double MIN_PROPORTION = 1e-12;
153 if ( xRange < MIN_PROPORTION || yRange < MIN_PROPORTION )
154 {
155 mValid = false;
156 return;
157 }
158 }
159
160 const double myHeight = mSize.height();
161 const double myWidth = mSize.width();
162
163 if ( !myWidth || !myHeight )
164 {
165 mValid = false;
166 return;
167 }
168
169 // calculate the translation and scaling parameters
170 const double mapUnitsPerPixelY = mExtent.height() / myHeight;
171 const double mapUnitsPerPixelX = mExtent.width() / myWidth;
172 mMapUnitsPerPixel = mapUnitsPerPixelY > mapUnitsPerPixelX ? mapUnitsPerPixelY : mapUnitsPerPixelX;
173
174 // calculate the actual extent of the mapCanvas
175 double dxmin = mExtent.xMinimum(), dxmax = mExtent.xMaximum(),
176 dymin = mExtent.yMinimum(), dymax = mExtent.yMaximum(), whitespace;
177
178 if ( mapUnitsPerPixelY > mapUnitsPerPixelX )
179 {
180 whitespace = ( ( myWidth * mMapUnitsPerPixel ) - mExtent.width() ) * 0.5;
181 dxmin -= whitespace;
182 dxmax += whitespace;
183 }
184 else
185 {
186 whitespace = ( ( myHeight * mMapUnitsPerPixel ) - mExtent.height() ) * 0.5;
187 dymin -= whitespace;
188 dymax += whitespace;
189 }
190
191 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
192
193 // update the scale
196
197 bool ok = true;
200 visibleExtent().center().x(),
201 visibleExtent().center().y(),
202 outputSize().width(),
203 outputSize().height(),
204 mRotation, &ok );
205
206 mValid = ok;
207
208#if 1 // set visible extent taking rotation in consideration
209 if ( mRotation )
210 {
211 const QgsPointXY p1 = mMapToPixel.toMapCoordinates( QPoint( 0, 0 ) );
212 const QgsPointXY p2 = mMapToPixel.toMapCoordinates( QPoint( 0, myHeight ) );
213 const QgsPointXY p3 = mMapToPixel.toMapCoordinates( QPoint( myWidth, 0 ) );
214 const QgsPointXY p4 = mMapToPixel.toMapCoordinates( QPoint( myWidth, myHeight ) );
215 dxmin = std::min( p1.x(), std::min( p2.x(), std::min( p3.x(), p4.x() ) ) );
216 dymin = std::min( p1.y(), std::min( p2.y(), std::min( p3.y(), p4.y() ) ) );
217 dxmax = std::max( p1.x(), std::max( p2.x(), std::max( p3.x(), p4.x() ) ) );
218 dymax = std::max( p1.y(), std::max( p2.y(), std::max( p3.y(), p4.y() ) ) );
219 mVisibleExtent.set( dxmin, dymin, dxmax, dymax );
220 }
221#endif
222
223 QgsDebugMsgLevel( QStringLiteral( "Map units per pixel (x,y) : %1, %2" ).arg( qgsDoubleToString( mapUnitsPerPixelX ), qgsDoubleToString( mapUnitsPerPixelY ) ), 5 );
224 QgsDebugMsgLevel( QStringLiteral( "Pixmap dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mSize.width() ), qgsDoubleToString( mSize.height() ) ), 5 );
225 QgsDebugMsgLevel( QStringLiteral( "Extent dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mExtent.width() ), qgsDoubleToString( mExtent.height() ) ), 5 );
227 QgsDebugMsgLevel( QStringLiteral( "Adjusted map units per pixel (x,y) : %1, %2" ).arg( qgsDoubleToString( mVisibleExtent.width() / myWidth ), qgsDoubleToString( mVisibleExtent.height() / myHeight ) ), 5 );
228 QgsDebugMsgLevel( QStringLiteral( "Recalced pixmap dimensions (x,y) : %1, %2" ).arg( qgsDoubleToString( mVisibleExtent.width() / mMapUnitsPerPixel ), qgsDoubleToString( mVisibleExtent.height() / mMapUnitsPerPixel ) ), 5 );
229 QgsDebugMsgLevel( QStringLiteral( "Scale (assuming meters as map units) = 1:%1" ).arg( qgsDoubleToString( mScale ) ), 5 );
230 QgsDebugMsgLevel( QStringLiteral( "Rotation: %1 degrees" ).arg( mRotation ), 5 );
231 QgsDebugMsgLevel( QStringLiteral( "Extent: %1" ).arg( mExtent.asWktCoordinates() ), 5 );
232 QgsDebugMsgLevel( QStringLiteral( "Visible Extent: %1" ).arg( mVisibleExtent.asWktCoordinates() ), 5 );
233 QgsDebugMsgLevel( QStringLiteral( "Magnification factor: %1" ).arg( mMagnificationFactor ), 5 );
234
235}
236
237
239{
240 return mSize;
241}
242
244{
245 mSize = size;
246
248}
249
251{
252 return mDevicePixelRatio;
253}
254
256{
257 mDevicePixelRatio = dpr;
259}
260
262{
263 return outputSize() * mDevicePixelRatio;
264}
265
267{
268 return mDpi;
269}
270
272{
273 mDpi = dpi;
274
276}
277
279{
280 return mDpiTarget;
281}
282
284{
285 mDpiTarget = dpi;
286}
287
288QStringList QgsMapSettings::layerIds( bool expandGroupLayers ) const
289{
290 const QList<QgsMapLayer * > mapLayers = layers( expandGroupLayers );
291 QStringList res;
292 res.reserve( mapLayers.size() );
293 for ( const QgsMapLayer *layer : mapLayers )
294 res << layer->id();
295 return res;
296}
297
298QList<QgsMapLayer *> QgsMapSettings::layers( bool expandGroupLayers ) const
299{
300 const QList<QgsMapLayer *> actualLayers = _qgis_listQPointerToRaw( mLayers );
301 if ( !expandGroupLayers )
302 return actualLayers;
303
304 QList< QgsMapLayer * > result;
305
306 std::function< void( const QList< QgsMapLayer * >& layers ) > expandLayers;
307 expandLayers = [&result, &expandLayers]( const QList< QgsMapLayer * > &layers )
308 {
309 for ( QgsMapLayer *layer : layers )
310 {
311 if ( QgsGroupLayer *groupLayer = qobject_cast< QgsGroupLayer * >( layer ) )
312 {
313 expandLayers( groupLayer->childLayers() );
314 }
315 else
316 {
317 result << layer;
318 }
319 }
320 };
321
322 expandLayers( actualLayers );
323 return result;
324}
325
326template<typename T>
327QVector<T> QgsMapSettings::layers() const
328{
329 const QList<QgsMapLayer *> actualLayers = _qgis_listQPointerToRaw( mLayers );
330
331 QVector<T> layers;
332 for ( QgsMapLayer *layer : actualLayers )
333 {
334 T tLayer = qobject_cast<T>( layer );
335 if ( tLayer )
336 {
337 layers << tLayer;
338 }
339 }
340 return layers;
341}
342
343void QgsMapSettings::setLayers( const QList<QgsMapLayer *> &layers )
344{
345 // filter list, removing null layers and non-spatial layers
346 auto filteredList = layers;
347 filteredList.erase( std::remove_if( filteredList.begin(), filteredList.end(),
348 []( QgsMapLayer * layer )
349 {
350 return !layer || !layer->isSpatial();
351 } ), filteredList.end() );
352
353 mLayers = _qgis_listRawToQPointer( filteredList );
354}
355
356QMap<QString, QString> QgsMapSettings::layerStyleOverrides() const
357{
359}
360
361void QgsMapSettings::setLayerStyleOverrides( const QMap<QString, QString> &overrides )
362{
363 mLayerStyleOverrides = overrides;
364}
365
367{
368 mDestCRS = crs;
370 // Since the map units have changed, force a recalculation of the scale.
372}
373
378
379bool QgsMapSettings::setEllipsoid( const QString &ellipsoid )
380{
382 if ( !params.valid )
383 {
384 return false;
385 }
386 else
387 {
389 return true;
390 }
391}
392
397
399{
400 if ( on )
401 mFlags |= flag;
402 else
403 mFlags &= ~( static_cast< int >( flag ) );
404}
405
410
412{
413 return mFlags.testFlag( flag );
414}
415
420
425
431
433{
434 return mValid;
435}
436
441
443{
444 QPolygonF poly;
445
446 const QSize &sz = outputSize();
447 const QgsMapToPixel &m2p = mapToPixel();
448
449 poly << m2p.toMapCoordinates( 0.0, 0.0 ).toQPointF();
450 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), 0.0 ).toQPointF();
451 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() ), static_cast<double>( sz.height() ) ).toQPointF();
452 poly << m2p.toMapCoordinates( 0.0, static_cast<double>( sz.height() ) ).toQPointF();
453
454 return poly;
455}
456
458{
459 QPolygonF poly;
460
461 const QSize &sz = outputSize();
462 const QgsMapToPixel &m2p = mapToPixel();
463
464 // Transform tilebuffer in pixel.
465 // Original tilebuffer is in pixel and transformed only according
466 // extent width (see QgsWmsRenderContext::mapTileBuffer)
467
468 const double mapUnitsPerPixel = mExtent.width() / sz.width();
469 const double buffer = mExtentBuffer / mapUnitsPerPixel;
470
471 poly << m2p.toMapCoordinates( -buffer, -buffer ).toQPointF();
472 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), -buffer ).toQPointF();
473 poly << m2p.toMapCoordinates( static_cast<double>( sz.width() + buffer ), static_cast<double>( sz.height() + buffer ) ).toQPointF();
474 poly << m2p.toMapCoordinates( -buffer, static_cast<double>( sz.height() + buffer ) ).toQPointF();
475
476 return poly;
477}
478
480{
481 return mMapUnitsPerPixel;
482}
483
485{
486 return mScale;
487}
488
490{
491#ifdef QGISDEBUG
492 if ( !mHasTransformContext )
493 QgsDebugMsgLevel( QStringLiteral( "No QgsCoordinateTransformContext context set for transform" ), 4 );
494#endif
495
496 return mTransformContext;
497}
498
500{
501 mTransformContext = context;
502#ifdef QGISDEBUG
503 mHasTransformContext = true;
504#endif
505}
506
508{
509 if ( !layer )
510 return QgsCoordinateTransform();
511
513}
514
516{
517 // Output width in inches
518 const double outputWidthInInches = outputSize().width() / outputDpi();
519
520 // Desired visible width (honouring scale)
521 const double scaledWidthInInches = outputWidthInInches * scale;
522
524 {
525 // Start with some fraction of the current extent around the center
526 const double delta = mExtent.width() / 100.;
527 QgsRectangle ext( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
528 // Get scale at extent, and then scale extent to the desired scale
529 const double testScale = mScaleCalculator.calculate( ext, outputSize().width() );
530 ext.scale( scale / testScale );
531 return ext;
532 }
533 else
534 {
535 // Conversion from inches to mapUnits - this is safe to use, because we know here that the map units AREN'T in degrees
536 const double conversionFactor = QgsUnitTypes::fromUnitToUnitFactor( Qgis::DistanceUnit::Feet, mapUnits() ) / 12;
537
538 const double delta = 0.5 * scaledWidthInInches * conversionFactor;
539 return QgsRectangle( center.x() - delta, center.y() - delta, center.x() + delta, center.y() + delta );
540 }
541}
542
544{
545 return mScaleCalculator.calculate( extent, outputSize().width() );
546}
547
548double QgsMapSettings::layerToMapUnits( const QgsMapLayer *layer, const QgsRectangle &referenceExtent ) const
549{
550 return layerTransform( layer ).scaleFactor( referenceExtent );
551}
552
553
555{
556 try
557 {
559 if ( ct.isValid() )
560 {
561 QgsDebugMsgLevel( QStringLiteral( "sourceCrs = %1" ).arg( ct.sourceCrs().authid() ), 3 );
562 QgsDebugMsgLevel( QStringLiteral( "destCRS = %1" ).arg( ct.destinationCrs().authid() ), 3 );
563 QgsDebugMsgLevel( QStringLiteral( "extent %1" ).arg( extent.toString() ), 3 );
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 {
585 if ( ct.isValid() )
586 {
587 QgsDebugMsgLevel( QStringLiteral( "sourceCrs = %1" ).arg( ct.sourceCrs().authid() ), 3 );
588 QgsDebugMsgLevel( QStringLiteral( "destCRS = %1" ).arg( ct.destinationCrs().authid() ), 3 );
589 QgsDebugMsgLevel( QStringLiteral( "extent = %1" ).arg( extent.toString() ), 3 );
591 }
592 }
593 catch ( QgsCsException &cse )
594 {
595 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
596 }
597
598 QgsDebugMsgLevel( QStringLiteral( "proj extent = %1" ).arg( extent.toString() ), 3 );
599
600 return extent;
601}
602
603
605{
606 try
607 {
608 const QgsCoordinateTransform ct = layerTransform( layer );
609 if ( ct.isValid() )
610 point = ct.transform( point, Qgis::TransformDirection::Forward );
611 }
612 catch ( QgsCsException &cse )
613 {
614 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
615 }
616
617 return point;
618}
619
621{
622 double x = point.x();
623 double y = point.y();
624 double z = point.z();
625 const double m = point.m();
626
627 try
628 {
629 const QgsCoordinateTransform ct = layerTransform( layer );
630 if ( ct.isValid() )
632 }
633 catch ( QgsCsException &cse )
634 {
635 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
636 }
637
638 return QgsPoint( x, y, z, m );
639}
640
641
643{
644 try
645 {
646 const QgsCoordinateTransform ct = layerTransform( layer );
647 if ( ct.isValid() )
649 }
650 catch ( QgsCsException &cse )
651 {
652 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
653 }
654
655 return rect;
656}
657
658
660{
661 try
662 {
663 const QgsCoordinateTransform ct = layerTransform( layer );
664 if ( ct.isValid() )
665 point = ct.transform( point, Qgis::TransformDirection::Reverse );
666 }
667 catch ( QgsCsException &cse )
668 {
669 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
670 }
671
672 return point;
673}
674
676{
677 double x = point.x();
678 double y = point.y();
679 double z = point.z();
680 const double m = point.m();
681
682 try
683 {
684 const QgsCoordinateTransform ct = layerTransform( layer );
685 if ( ct.isValid() )
687 }
688 catch ( QgsCsException &cse )
689 {
690 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
691 }
692
693 return QgsPoint( x, y, z, m );
694}
695
696
698{
699 try
700 {
701 const QgsCoordinateTransform ct = layerTransform( layer );
702 if ( ct.isValid() )
704 }
705 catch ( QgsCsException &cse )
706 {
707 QgsMessageLog::logMessage( QObject::tr( "Transform error caught: %1" ).arg( cse.what() ), QObject::tr( "CRS" ) );
708 }
709
710 return rect;
711}
712
713
714
716{
717 // reset the map canvas extent since the extent may now be smaller
718 // We can't use a constructor since QgsRectangle normalizes the rectangle upon construction
721
722 // iterate through the map layers and test each layers extent
723 // against the current min and max values
724 QgsDebugMsgLevel( QStringLiteral( "Layer count: %1" ).arg( mLayers.count() ), 5 );
725 const auto constMLayers = mLayers;
726 for ( const QgsWeakMapLayerPointer &layerPtr : constMLayers )
727 {
728 if ( QgsMapLayer *lyr = layerPtr.data() )
729 {
730 QgsDebugMsgLevel( "Updating extent using " + lyr->name(), 5 );
731 QgsDebugMsgLevel( "Input extent: " + lyr->extent().toString(), 5 );
732
733 if ( lyr->extent().isNull() )
734 continue;
735
736 // Layer extents are stored in the coordinate system (CS) of the
737 // layer. The extent must be projected to the canvas CS
738 const QgsRectangle extent = layerExtentToOutputExtent( lyr, lyr->extent() );
739
740 QgsDebugMsgLevel( "Output extent: " + extent.toString(), 5 );
742 }
743 }
744
745 if ( fullExtent.width() == 0.0 || fullExtent.height() == 0.0 )
746 {
747 // If all of the features are at the one point, buffer the
748 // rectangle a bit. If they are all at zero, do something a bit
749 // more crude.
750
751 if ( fullExtent.xMinimum() == 0.0 && fullExtent.xMaximum() == 0.0 &&
752 fullExtent.yMinimum() == 0.0 && fullExtent.yMaximum() == 0.0 )
753 {
754 fullExtent.set( -1.0, -1.0, 1.0, 1.0 );
755 }
756 else
757 {
758 const double padFactor = 1e-8;
759 const double widthPad = fullExtent.xMinimum() * padFactor;
760 const double heightPad = fullExtent.yMinimum() * padFactor;
761 const double xmin = fullExtent.xMinimum() - widthPad;
762 const double xmax = fullExtent.xMaximum() + widthPad;
763 const double ymin = fullExtent.yMinimum() - heightPad;
764 const double ymax = fullExtent.yMaximum() + heightPad;
765 fullExtent.set( xmin, ymin, xmax, ymax );
766 }
767 }
768
769 QgsDebugMsgLevel( "Full extent: " + fullExtent.toString(), 5 );
770 return fullExtent;
771}
772
773
774void QgsMapSettings::readXml( QDomNode &node )
775{
776 // set destination CRS
778 const QDomNode srsNode = node.namedItem( QStringLiteral( "destinationsrs" ) );
779 if ( !srsNode.isNull() )
780 {
781 srs.readXml( srsNode );
782 }
783 setDestinationCrs( srs );
784
785 // set extent
786 const QDomNode extentNode = node.namedItem( QStringLiteral( "extent" ) );
787 const QgsRectangle aoi = QgsXmlUtils::readRectangle( extentNode.toElement() );
788 setExtent( aoi );
789
790 // set rotation
791 const QDomNode rotationNode = node.namedItem( QStringLiteral( "rotation" ) );
792 const QString rotationVal = rotationNode.toElement().text();
793 if ( ! rotationVal.isEmpty() )
794 {
795 const double rot = rotationVal.toDouble();
796 setRotation( rot );
797 }
798
799 //render map tile
800 const QDomElement renderMapTileElem = node.firstChildElement( QStringLiteral( "rendermaptile" ) );
801 if ( !renderMapTileElem.isNull() )
802 {
803 setFlag( Qgis::MapSettingsFlag::RenderMapTile, renderMapTileElem.text() == QLatin1String( "1" ) );
804 }
805}
806
807
808
809void QgsMapSettings::writeXml( QDomNode &node, QDomDocument &doc )
810{
811 // units
812 node.appendChild( QgsXmlUtils::writeMapUnits( mapUnits(), doc ) );
813
814 // Write current view extents
815 node.appendChild( QgsXmlUtils::writeRectangle( extent(), doc ) );
816
817 // Write current view rotation
818 QDomElement rotNode = doc.createElement( QStringLiteral( "rotation" ) );
819 rotNode.appendChild(
820 doc.createTextNode( qgsDoubleToString( rotation() ) )
821 );
822 node.appendChild( rotNode );
823
824 // destination CRS
825 if ( mDestCRS.isValid() )
826 {
827 QDomElement srsNode = doc.createElement( QStringLiteral( "destinationsrs" ) );
828 node.appendChild( srsNode );
829 mDestCRS.writeXml( srsNode, doc );
830 }
831
832 //render map tile
833 QDomElement renderMapTileElem = doc.createElement( QStringLiteral( "rendermaptile" ) );
834 const QDomText renderMapTileText = doc.createTextNode( testFlag( Qgis::MapSettingsFlag::RenderMapTile ) ? "1" : "0" );
835 renderMapTileElem.appendChild( renderMapTileText );
836 node.appendChild( renderMapTileElem );
837}
838
843
845{
846 mLabelBoundaryGeometry = boundary;
847}
848
850{
851 mClippingRegions.append( region );
852}
853
854void QgsMapSettings::setClippingRegions( const QList<QgsMapClippingRegion> &regions )
855{
856 mClippingRegions = regions;
857}
858
859QList<QgsMapClippingRegion> QgsMapSettings::clippingRegions() const
860{
861 return mClippingRegions;
862}
863
865{
866 mMaskRenderSettings = settings;
867}
868
870{
871 mRenderedFeatureHandlers.append( handler );
872}
873
874QList<QgsRenderedFeatureHandlerInterface *> QgsMapSettings::renderedFeatureHandlers() const
875{
876 return mRenderedFeatureHandlers;
877}
878
880{
881 return mZRange;
882}
883
885{
886 mZRange = zRange;
887}
888
893
898
900{
901 return mFrameRate;
902}
903
905{
906 mFrameRate = rate;
907}
908
910{
911 return mCurrentFrame;
912}
913
914void QgsMapSettings::setCurrentFrame( long long frame )
915{
916 mCurrentFrame = frame;
917}
918
923
928
Provides global constants and enumerations for use throughout the application.
Definition qgis.h:54
QFlags< MapSettingsFlag > MapSettingsFlags
Map settings flags.
Definition qgis.h:2673
@ NoSimplification
No simplification can be applied.
DistanceUnit
Units of distance.
Definition qgis.h:4843
@ Feet
Imperial feet.
@ Unknown
Unknown distance unit.
@ Degrees
Degrees, for planar geographic CRS distance measurements.
ScaleCalculationMethod
Scale calculation logic.
Definition qgis.h:5080
RendererUsage
Usage of the renderer.
Definition qgis.h:3313
@ Forward
Forward transform (from source to destination)
@ Reverse
Reverse/inverse transform (from destination to source)
MapSettingsFlag
Flags which adjust the way maps are rendered.
Definition qgis.h:2651
@ RenderMapTile
Draw map such that there are no problems between adjacent tiles.
Represents a coordinate reference system (CRS).
bool isValid() const
Returns whether this CRS is correctly initialized and usable.
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.
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:233
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:77
QgsCoordinateReferenceSystem crs
Definition qgsmaplayer.h:84
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
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.
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.
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...
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)
Restore the map settings from a XML 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.
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.
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:60
double y
Definition qgspointxy.h:64
double x
Definition qgspointxy.h:63
QPointF toQPointF() const
Converts a point to a QPointF.
Definition qgspointxy.h:165
Point geometry type, with support for z-dimension and m-values.
Definition qgspoint.h:49
double z
Definition qgspoint.h:54
double x
Definition qgspoint.h:52
double m
Definition qgspoint.h:55
double y
Definition qgspoint.h:53
A rectangle specified with double values.
Q_INVOKABLE 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.
double xMinimum
double yMinimum
double xMaximum
Q_INVOKABLE QString asWktCoordinates() const
Returns a string representation of the rectangle in WKT format.
void set(const QgsPointXY &p1, const QgsPointXY &p2, bool normalize=true)
Sets the rectangle from two QgsPoints.
double yMaximum
void combineExtentWith(const QgsRectangle &rect)
Expands the rectangle so that it covers both the original rectangle and the given rectangle.
QgsPointXY center
void setNull()
Mark a rectangle as being null (holding no spatial information).
bool isFinite() const
Returns true if the rectangle has finite boundaries.
An interface for classes which provide 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::ScaleCalculationMethod method() const
Returns the method to use for map scale calculations.
Qgis::DistanceUnit mapUnits() const
Returns current map units.
void setMethod(Qgis::ScaleCalculationMethod method)
Sets the method to use for map scale calculations.
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
void setSimplifyHints(Qgis::VectorRenderingSimplificationFlags simplifyHints)
Sets the simplification hints of the vector layer managed.
static QDomElement writeRectangle(const QgsRectangle &rect, QDomDocument &doc, const QString &elementName=QStringLiteral("extent"))
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:6203
bool qgsDoubleNear(double a, double b, double epsilon=4 *std::numeric_limits< double >::epsilon())
Compare two doubles (but allow some difference)
Definition qgis.h:6286
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:41
QPointer< QgsMapLayer > QgsWeakMapLayerPointer
Weak pointer for QgsMapLayer.
const QgsCoordinateReferenceSystem & crs
Contains parameters for an ellipsoid.
bool valid
Whether ellipsoid parameters are valid.