QGIS API Documentation 3.43.0-Master (b60ef06885e)
qgsscalecalculator.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsscalecalculator.h
3 Calculates scale based on map extent and units
4 -------------------
5 begin : May 18, 2004
6 copyright : (C) 2004 by Gary E.Sherman
7 email : sherman at mrcc.com
8 ***************************************************************************/
9
10/***************************************************************************
11 * *
12 * This program is free software; you can redistribute it and/or modify *
13 * it under the terms of the GNU General Public License as published by *
14 * the Free Software Foundation; either version 2 of the License, or *
15 * (at your option) any later version. *
16 * *
17 ***************************************************************************/
18
19#include <cmath>
20#include "qgslogger.h"
21#include "qgsscalecalculator.h"
22#include "qgsrectangle.h"
23#include "qgsunittypes.h"
24#include <QSizeF>
25
27 : mDpi( dpi )
28 , mMapUnits( mapUnits )
29{}
30
35
37{
38 mDpi = dpi;
39}
41{
42 return mDpi;
43}
44
46{
47 QgsDebugMsgLevel( QStringLiteral( "Map units set to %1" ).arg( qgsEnumValueToKey( mapUnits ) ), 3 );
48 mMapUnits = mapUnits;
49}
50
52{
53 QgsDebugMsgLevel( QStringLiteral( "Map units returned as %1" ).arg( qgsEnumValueToKey( mMapUnits ) ), 4 );
54 return mMapUnits;
55}
56
57double QgsScaleCalculator::calculate( const QgsRectangle &mapExtent, double canvasWidth ) const
58{
59 if ( qgsDoubleNear( canvasWidth, 0. ) || qgsDoubleNear( mDpi, 0.0 ) )
60 {
61 QgsDebugError( QStringLiteral( "Can't calculate scale from the input values" ) );
62 return 0;
63 }
64
65 double conversionFactor = 0;
66 double delta = 0;
67 calculateMetrics( mapExtent, delta, conversionFactor );
68
69 const double scale = ( delta * conversionFactor ) / ( static_cast< double >( canvasWidth ) / mDpi );
70 QgsDebugMsgLevel( QStringLiteral( "scale = %1 conversionFactor = %2" ).arg( scale ).arg( conversionFactor ), 4 );
71 return scale;
72}
73
74QSizeF QgsScaleCalculator::calculateImageSize( const QgsRectangle &mapExtent, double scale ) const
75{
76 if ( qgsDoubleNear( scale, 0.0 ) || qgsDoubleNear( mDpi, 0.0 ) )
77 {
78 QgsDebugError( QStringLiteral( "Can't calculate image size from the input values" ) );
79 return QSizeF();
80 }
81 double conversionFactor = 0;
82 double delta = 0;
83
84 calculateMetrics( mapExtent, delta, conversionFactor );
85 const double imageWidth = ( delta * conversionFactor ) / ( static_cast< double >( scale ) ) * mDpi;
86 const double deltaHeight = ( mapExtent.yMaximum() - mapExtent.yMinimum() ) * delta / ( mapExtent.xMaximum() - mapExtent.xMinimum() );
87 const double imageHeight = ( deltaHeight * conversionFactor ) / ( static_cast< double >( scale ) ) * mDpi;
88
89 QgsDebugMsgLevel( QStringLiteral( "imageWidth = %1 imageHeight = %2 conversionFactor = %3" )
90 .arg( imageWidth ).arg( imageHeight ).arg( conversionFactor ), 4 );
91
92 return QSizeF( imageWidth, imageHeight );
93}
94
95void QgsScaleCalculator::calculateMetrics( const QgsRectangle &mapExtent, double &delta, double &conversionFactor ) const
96{
97 delta = mapExtent.xMaximum() - mapExtent.xMinimum();
98
99 switch ( mMapUnits )
100 {
102 conversionFactor = 1;
103 break;
104
152 // convert to inches
153 conversionFactor = QgsUnitTypes::fromUnitToUnitFactor( mMapUnits, Qgis::DistanceUnit::Inches );
154 break;
155
157 // assume degrees to maintain old API
158 [[fallthrough]];
159
161 // degrees require conversion to meters first
162 conversionFactor = 39.3700787;
163 delta = calculateGeographicDistance( mapExtent );
164 break;
165 }
166}
167
169{
170 switch ( mMethod )
171 {
174 mapExtent.xMinimum(), mapExtent.xMaximum() );
175
177 return calculateGeographicDistanceAtLatitude( ( mapExtent.yMaximum() + mapExtent.yMinimum() ) * 0.5,
178 mapExtent.xMinimum(), mapExtent.xMaximum() );
179
182 mapExtent.xMinimum(), mapExtent.xMaximum() );
183
185 {
186 const double dTop = calculateGeographicDistanceAtLatitude( mapExtent.yMaximum(),
187 mapExtent.xMinimum(), mapExtent.xMaximum() );
188 const double dMiddle = calculateGeographicDistanceAtLatitude( ( mapExtent.yMaximum() + mapExtent.yMinimum() ) * 0.5,
189 mapExtent.xMinimum(), mapExtent.xMaximum() );
190 const double dBottom = calculateGeographicDistanceAtLatitude( mapExtent.yMinimum(),
191 mapExtent.xMinimum(), mapExtent.xMaximum() );
192 return ( dTop + dMiddle + dBottom ) / 3.0;
193 }
194
197 mapExtent.xMinimum(), mapExtent.xMaximum() );
198 }
199 // unreachable!
200 return 0;
201}
202
203double QgsScaleCalculator::calculateGeographicDistanceAtLatitude( double lat, double longitude1, double longitude2 ) const
204{
205 // need to calculate the x distance in meters
206
207 // Note this is an approximation (although very close) but calculating scale
208 // for geographic data over large extents is quasi-meaningless
209
210 // The distance between two points on a sphere can be estimated
211 // using the Haversine formula. This gives the shortest distance
212 // between two points on the sphere. However, what we're after is
213 // the distance from the left of the given extent and the right of
214 // it. This is not necessarily the shortest distance between two
215 // points on a sphere.
216 //
217 // The code below uses the Haversine formula, but with some changes
218 // to cope with the above problem, and also to deal with the extent
219 // possibly extending beyond +/-180 degrees:
220 //
221 // - Use the Halversine formula to calculate the distance from -90 to
222 // +90 degrees at desired latitude.
223 // - Scale this distance by the number of degrees between
224 // the two longitudes
225
226
227 // - TODO: respect the actual ellipsoid parameters!!
228
229 // For a longitude change of 180 degrees
230 static const double RADS = ( 4.0 * std::atan( 1.0 ) ) / 180.0;
231 const double a = std::pow( std::cos( lat * RADS ), 2 );
232 const double c = 2.0 * std::atan2( std::sqrt( a ), std::sqrt( 1.0 - a ) );
233 static const double RA = 6378000; // [m]
234 // The eccentricity. This comes from sqrt(1.0 - rb*rb/(ra*ra)) with rb set
235 // to 6357000 m.
236 static const double E = 0.0810820288;
237 const double radius = RA * ( 1.0 - E * E ) /
238 std::pow( 1.0 - E * E * std::sin( lat * RADS ) * std::sin( lat * RADS ), 1.5 );
239 const double meters = ( longitude2 - longitude1 ) / 180.0 * radius * c;
240
241 QgsDebugMsgLevel( "Distance across map extent (m): " + QString::number( meters ), 4 );
242
243 return meters;
244}
DistanceUnit
Units of distance.
Definition qgis.h:4843
@ YardsBritishSears1922Truncated
British yards (Sears 1922 truncated)
@ Feet
Imperial feet.
@ MilesUSSurvey
US Survey miles.
@ LinksBritishSears1922
British links (Sears 1922)
@ YardsBritishBenoit1895A
British yards (Benoit 1895 A)
@ LinksBritishBenoit1895A
British links (Benoit 1895 A)
@ Centimeters
Centimeters.
@ YardsIndian1975
Indian yards (1975)
@ FeetUSSurvey
US Survey feet.
@ Millimeters
Millimeters.
@ FeetBritishSears1922
British feet (Sears 1922)
@ YardsClarkes
Clarke's yards.
@ YardsIndian
Indian yards.
@ FeetBritishBenoit1895B
British feet (Benoit 1895 B)
@ Miles
Terrestrial miles.
@ LinksUSSurvey
US Survey links.
@ ChainsUSSurvey
US Survey chains.
@ FeetClarkes
Clarke's feet.
@ Unknown
Unknown distance unit.
@ Yards
Imperial yards.
@ FeetBritish1936
British feet (1936)
@ FeetIndian1962
Indian feet (1962)
@ YardsBritishSears1922
British yards (Sears 1922)
@ FeetIndian1937
Indian feet (1937)
@ YardsIndian1937
Indian yards (1937)
@ Degrees
Degrees, for planar geographic CRS distance measurements.
@ ChainsBritishBenoit1895B
British chains (Benoit 1895 B)
@ LinksBritishSears1922Truncated
British links (Sears 1922 truncated)
@ ChainsBritishBenoit1895A
British chains (Benoit 1895 A)
@ YardsBritishBenoit1895B
British yards (Benoit 1895 B)
@ FeetBritish1865
British feet (1865)
@ YardsIndian1962
Indian yards (1962)
@ FeetBritishSears1922Truncated
British feet (Sears 1922 truncated)
@ MetersGermanLegal
German legal meter.
@ LinksBritishBenoit1895B
British links (Benoit 1895 B)
@ ChainsInternational
International chains.
@ LinksInternational
International links.
@ ChainsBritishSears1922Truncated
British chains (Sears 1922 truncated)
@ FeetIndian
Indian (geodetic) feet.
@ NauticalMiles
Nautical miles.
@ ChainsClarkes
Clarke's chains.
@ LinksClarkes
Clarke's links.
@ ChainsBritishSears1922
British chains (Sears 1922)
@ Kilometers
Kilometers.
@ FeetIndian1975
Indian feet (1975)
@ FeetGoldCoast
Gold Coast feet.
@ FeetBritishBenoit1895A
British feet (Benoit 1895 A)
ScaleCalculationMethod
Scale calculation logic.
Definition qgis.h:5080
@ HorizontalTop
Calculate horizontally, across top of map.
@ HorizontalMiddle
Calculate horizontally, across midle of map.
@ AtEquator
Always calculate the scale at the equator, regardless of the actual visible map extent....
@ HorizontalAverage
Calculate horizontally, using the average of the top, middle and bottom scales.
@ HorizontalBottom
Calculate horizontally, across bottom of map.
A rectangle specified with double values.
double xMinimum
double yMinimum
double xMaximum
double yMaximum
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.
double calculateGeographicDistance(const QgsRectangle &mapExtent) const
Calculate the distance in meters, horizontally across the specified map extent (in geographic coordin...
QSizeF calculateImageSize(const QgsRectangle &mapExtent, double scale) const
Calculate the image size in pixel (physical) units.
Qgis::ScaleCalculationMethod method() const
Returns the method to use for map scale calculations.
double dpi() const
Returns the DPI (dots per inch) used in scale calculations.
Qgis::DistanceUnit mapUnits() const
Returns current map units.
void setMethod(Qgis::ScaleCalculationMethod method)
Sets the method to use for map scale calculations.
QgsScaleCalculator(double dpi=0, Qgis::DistanceUnit mapUnits=Qgis::DistanceUnit::Meters)
Constructor.
double calculateGeographicDistanceAtLatitude(double latitude, double longitude1, double longitude2) const
Calculate the distance in meters, horizontally between two longitudes at a specified latitude.
static Q_INVOKABLE double fromUnitToUnitFactor(Qgis::DistanceUnit fromUnit, Qgis::DistanceUnit toUnit)
Returns the conversion factor between the specified distance units.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
QString qgsEnumValueToKey(const T &value, bool *returnOk=nullptr)
Returns the value for the given key of an enum.
Definition qgis.h:6477
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
#define QgsDebugError(str)
Definition qgslogger.h:40