-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
qgscoordinatereferencesystem.cpp
1544 lines (1342 loc) · 46.6 KB
/
qgscoordinatereferencesystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
qgscoordinatereferencesystem.cpp
-------------------
begin : 2007
copyright : (C) 2007 by Gary E. Sherman
email : sherman@mrcc.com
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgscoordinatereferencesystem.h"
#include <cmath>
#include <QDir>
#include <QDomNode>
#include <QDomElement>
#include <QFileInfo>
#include <QRegExp>
#include <QTextStream>
#include "qgsapplication.h"
#include "qgscrscache.h"
#include "qgslogger.h"
#include "qgsmessagelog.h"
#include "qgis.h" //const vals declared here
#include <sqlite3.h>
#include <proj_api.h>
//gdal and ogr includes (needed for == operator)
#include <ogr_srs_api.h>
#include <cpl_error.h>
#include <cpl_conv.h>
CUSTOM_CRS_VALIDATION QgsCoordinateReferenceSystem::mCustomSrsValidation = NULL;
//--------------------------
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem()
: mMapUnits( QGis::UnknownUnit )
, mIsValidFlag( 0 )
, mValidationHint( "" )
{
mCRS = OSRNewSpatialReference( NULL );
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( QString theDefinition )
: mMapUnits( QGis::UnknownUnit )
, mIsValidFlag( 0 )
, mValidationHint( "" )
{
mCRS = OSRNewSpatialReference( NULL );
createFromString( theDefinition );
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( const long theId, CrsType theType )
: mMapUnits( QGis::UnknownUnit )
, mIsValidFlag( 0 )
, mValidationHint( "" )
{
mCRS = OSRNewSpatialReference( NULL );
createFromId( theId, theType );
}
QgsCoordinateReferenceSystem::~QgsCoordinateReferenceSystem()
{
OSRDestroySpatialReference( mCRS );
}
bool QgsCoordinateReferenceSystem::createFromId( const long theId, CrsType theType )
{
bool result = false;
switch ( theType )
{
case InternalCrsId:
result = createFromSrsId( theId );
break;
case PostgisCrsId:
result = createFromSrid( theId );
break;
case EpsgCrsId:
result = createFromOgcWmsCrs( QString( "EPSG:%1" ).arg( theId ) );
break;
default:
//THIS IS BAD...THIS PART OF CODE SHOULD NEVER BE REACHED...
QgsDebugMsg( "Unexpected case reached!" );
};
return result;
}
bool QgsCoordinateReferenceSystem::createFromString( const QString theDefinition )
{
bool result = false;
QRegExp reCrsId( "^(epsg|postgis|internal)\\:(\\d+)$", Qt::CaseInsensitive );
if ( reCrsId.indexIn( theDefinition ) == 0 )
{
QString authName = reCrsId.cap( 1 ).toLower();
CrsType type = InternalCrsId;
if ( authName == "epsg" )
type = EpsgCrsId;
if ( authName == "postgis" )
type = PostgisCrsId;
long id = reCrsId.cap( 2 ).toLong();
result = createFromId( id, type );
}
else
{
QRegExp reCrsStr( "^(?:(wkt|proj4)\\:)?(.+)$", Qt::CaseInsensitive );
if ( reCrsStr.indexIn( theDefinition ) == 0 )
{
if ( reCrsStr.cap( 1 ).toLower() == "proj4" )
{
result = createFromProj4( reCrsStr.cap( 2 ) );
}
else
{
result = createFromWkt( reCrsStr.cap( 2 ) );
}
}
}
return result;
}
bool QgsCoordinateReferenceSystem::createFromOgcWmsCrs( QString theCrs )
{
QRegExp re( "(user|custom|qgis):(\\d+)", Qt::CaseInsensitive );
if ( re.exactMatch( theCrs ) && createFromSrsId( re.cap( 2 ).toInt() ) )
{
return true;
}
if ( loadFromDb( QgsApplication::srsDbFilePath(), "lower(auth_name||':'||auth_id)", theCrs.toLower() ) )
return true;
if ( theCrs.compare( "CRS:84", Qt::CaseInsensitive ) == 0 )
{
createFromSrsId( GEOCRS_ID );
return true;
}
return false;
}
QgsCoordinateReferenceSystem::QgsCoordinateReferenceSystem( const QgsCoordinateReferenceSystem &srs )
{
mCRS = OSRNewSpatialReference( NULL );
*this = srs;
}
// Assignment operator
QgsCoordinateReferenceSystem& QgsCoordinateReferenceSystem::operator=( const QgsCoordinateReferenceSystem & srs )
{
if ( &srs != this )
{
mSrsId = srs.mSrsId;
mDescription = srs.mDescription;
mProjectionAcronym = srs.mProjectionAcronym;
mEllipsoidAcronym = srs.mEllipsoidAcronym;
mGeoFlag = srs.mGeoFlag;
mAxisInverted = srs.mAxisInverted;
mMapUnits = srs.mMapUnits;
mSRID = srs.mSRID;
mAuthId = srs.mAuthId;
mIsValidFlag = srs.mIsValidFlag;
mValidationHint = srs.mValidationHint;
mWkt = srs.mWkt;
if ( mIsValidFlag )
{
OSRDestroySpatialReference( mCRS );
mCRS = OSRClone( srs.mCRS );
}
}
return *this;
}
// Misc helper functions -----------------------
void QgsCoordinateReferenceSystem::validate()
{
if ( mIsValidFlag )
return;
// try to validate using custom validation routines
if ( mCustomSrsValidation )
mCustomSrsValidation( this );
if ( !mIsValidFlag )
// set the default
createFromOgcWmsCrs( GEO_EPSG_CRS_AUTHID );
}
bool QgsCoordinateReferenceSystem::createFromSrid( long id )
{
return loadFromDb( QgsApplication::srsDbFilePath(), "srid", QString::number( id ) );
}
bool QgsCoordinateReferenceSystem::createFromEpsg( long id )
{
return createFromOgcWmsCrs( QString( "EPSG:%1" ).arg( id ) );
}
bool QgsCoordinateReferenceSystem::createFromSrsId( long id )
{
return loadFromDb( id < USER_CRS_START_ID ? QgsApplication::srsDbFilePath() : QgsApplication::qgisUserDbFilePath(),
"srs_id", QString::number( id ) );
}
bool QgsCoordinateReferenceSystem::loadFromDb( QString db, QString expression, QString value )
{
QgsDebugMsgLevel( "load CRS from " + db + " where " + expression + " is " + value, 3 );
mIsValidFlag = false;
mWkt.clear();
QFileInfo myInfo( db );
if ( !myInfo.exists() )
{
QgsDebugMsg( "failed : " + db + " does not exist!" );
return mIsValidFlag;
}
sqlite3 *myDatabase;
const char *myTail;
sqlite3_stmt *myPreparedStatement;
int myResult;
//check the db is available
myResult = openDb( db, &myDatabase );
if ( myResult != SQLITE_OK )
{
QgsDebugMsg( "failed : " + db + " could not be opened!" );
return mIsValidFlag;
}
/*
srs_id INTEGER PRIMARY KEY,
description text NOT NULL,
projection_acronym text NOT NULL,
ellipsoid_acronym NOT NULL,
parameters text NOT NULL,
srid integer NOT NULL,
auth_name varchar NOT NULL,
auth_id integer NOT NULL,
is_geo integer NOT NULL);
*/
QString mySql = "select srs_id,description,projection_acronym,ellipsoid_acronym,parameters,srid,auth_name||':'||auth_id,is_geo from tbl_srs where " + expression + "=" + quotedValue( value ) + " order by deprecated";
myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK && sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
{
mSrsId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 0 ) ).toLong();
mDescription = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 1 ) );
mProjectionAcronym = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 2 ) );
mEllipsoidAcronym = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 3 ) );
QString toProj4 = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 4 ) );
mSRID = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 5 ) ).toLong();
mAuthId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 6 ) );
mGeoFlag = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 7 ) ).toInt() != 0;
mAxisInverted = -1;
if ( mSrsId >= USER_CRS_START_ID && mAuthId.isEmpty() )
{
mAuthId = QString( "USER:%1" ).arg( mSrsId );
}
else if ( mAuthId.startsWith( "EPSG:", Qt::CaseInsensitive ) )
{
OSRDestroySpatialReference( mCRS );
mCRS = OSRNewSpatialReference( NULL );
mIsValidFlag = OSRSetFromUserInput( mCRS, mAuthId.toLower().toAscii() ) == OGRERR_NONE;
setMapUnits();
}
if ( !mIsValidFlag )
{
setProj4String( toProj4 );
}
}
else
{
QgsDebugMsg( "failed : " + mySql );
}
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
return mIsValidFlag;
}
bool QgsCoordinateReferenceSystem::axisInverted() const
{
if ( mAxisInverted == -1 )
{
OGRAxisOrientation orientation;
const char *axis0 = OSRGetAxis( mCRS, mGeoFlag ? "GEOGCS" : "PROJCS", 0, &orientation );
mAxisInverted = mGeoFlag
? ( orientation == OAO_East || orientation == OAO_West || orientation == OAO_Other )
: ( orientation == OAO_North || orientation == OAO_South );
QgsDebugMsg( QString( "srid:%1 axis0:%2 orientation:%3 inverted:%4" ).arg( mSRID ).arg( axis0 ).arg( OSRAxisEnumToName( orientation ) ).arg( mAxisInverted ) );
Q_UNUSED( axis0 );
}
return mAxisInverted != 0;
}
bool QgsCoordinateReferenceSystem::createFromWkt( QString theWkt )
{
mIsValidFlag = false;
mWkt.clear();
if ( theWkt.isEmpty() )
{
QgsDebugMsg( "theWkt is uninitialised, operation failed" );
return mIsValidFlag;
}
QgsDebugMsg( "wkt: " + theWkt );
QByteArray ba = theWkt.toLatin1();
const char *pWkt = ba.data();
OGRErr myInputResult = OSRImportFromWkt( mCRS, ( char ** ) & pWkt );
if ( myInputResult != OGRERR_NONE )
{
QgsDebugMsg( "\n---------------------------------------------------------------" );
QgsDebugMsg( "This CRS could *** NOT *** be set from the supplied Wkt " );
QgsDebugMsg( "INPUT: " + theWkt );
QgsDebugMsg( QString( "UNUSED WKT: %1" ).arg( pWkt ) );
QgsDebugMsg( "---------------------------------------------------------------\n" );
return mIsValidFlag;
}
if ( OSRAutoIdentifyEPSG( mCRS ) == OGRERR_NONE )
{
QString authid = QString( "%1:%2" )
.arg( OSRGetAuthorityName( mCRS, NULL ) )
.arg( OSRGetAuthorityCode( mCRS, NULL ) );
QgsDebugMsg( "authid recognized as " + authid );
return createFromOgcWmsCrs( authid );
}
// always morph from esri as it doesn't hurt anything
// FW: Hey, that's not right! It can screw stuff up! Disable
//myOgrSpatialRef.morphFromESRI();
// create the proj4 structs needed for transforming
char *proj4src = NULL;
OSRExportToProj4( mCRS, &proj4src );
//now that we have the proj4string, delegate to createFromProj4 so
// that we can try to fill in the remaining class members...
//create from Proj will set the isValidFlag
if ( !createFromProj4( proj4src ) )
{
CPLFree( proj4src );
// try fixed up version
OSRFixup( mCRS );
OSRExportToProj4( mCRS, &proj4src );
createFromProj4( proj4src );
}
CPLFree( proj4src );
return mIsValidFlag;
//setMapunits will be called by createfromproj above
}
bool QgsCoordinateReferenceSystem::isValid() const
{
return mIsValidFlag;
}
bool QgsCoordinateReferenceSystem::createFromProj4( const QString theProj4String )
{
//
// Examples:
// +proj=tmerc +lat_0=0 +lon_0=-62 +k=0.999500 +x_0=400000 +y_0=0
// +ellps=clrk80 +towgs84=-255,-15,71,0,0,0,0 +units=m +no_defs
//
// +proj=lcc +lat_1=46.8 +lat_0=46.8 +lon_0=2.337229166666664 +k_0=0.99987742
// +x_0=600000 +y_0=2200000 +a=6378249.2 +b=6356515.000000472 +units=m +no_defs
//
QgsDebugMsg( "proj4: " + theProj4String );
mIsValidFlag = false;
mWkt.clear();
QRegExp myProjRegExp( "\\+proj=(\\S+)" );
int myStart = myProjRegExp.indexIn( theProj4String );
if ( myStart == -1 )
{
QgsDebugMsg( "proj string supplied has no +proj argument" );
return mIsValidFlag;
}
mProjectionAcronym = myProjRegExp.cap( 1 );
QRegExp myEllipseRegExp( "\\+ellps=(\\S+)" );
myStart = myEllipseRegExp.indexIn( theProj4String );
if ( myStart == -1 )
{
QgsDebugMsg( "proj string supplied has no +ellps argument" );
mEllipsoidAcronym = "";
}
else
{
mEllipsoidAcronym = myEllipseRegExp.cap( 1 );
}
QRegExp myAxisRegExp( "\\+a=(\\S+)" );
myStart = myAxisRegExp.indexIn( theProj4String );
if ( myStart == -1 )
{
QgsDebugMsg( "proj string supplied has no +a argument" );
}
/*
* We try to match the proj string to and srsid using the following logic:
*
* - perform a whole text search on srs name (if not null). The srs name will
* have been set if this method has been delegated to from createFromWkt.
* Normally we wouldnt expect this to work, but its worth trying first
* as its quicker than methods below..
*/
long mySrsId = 0;
QgsCoordinateReferenceSystem::RecordMap myRecord;
/*
* - if the above does not match perform a whole text search on proj4 string (if not null)
*/
// QgsDebugMsg( "wholetext match on name failed, trying proj4string match" );
myRecord = getRecord( "select * from tbl_srs where parameters=" + quotedValue( theProj4String.trimmed() ) + " order by deprecated" );
if ( myRecord.empty() )
{
// Ticket #722 - aaronr
// Check if we can swap the lat_1 and lat_2 params (if they exist) to see if we match...
// First we check for lat_1 and lat_2
QRegExp myLat1RegExp( "\\+lat_1=\\S+" );
QRegExp myLat2RegExp( "\\+lat_2=\\S+" );
int myStart1 = 0;
int myLength1 = 0;
int myStart2 = 0;
int myLength2 = 0;
QString lat1Str = "";
QString lat2Str = "";
myStart1 = myLat1RegExp.indexIn( theProj4String, myStart1 );
myStart2 = myLat2RegExp.indexIn( theProj4String, myStart2 );
if ( myStart1 != -1 && myStart2 != -1 )
{
myLength1 = myLat1RegExp.matchedLength();
myLength2 = myLat2RegExp.matchedLength();
lat1Str = theProj4String.mid( myStart1 + LAT_PREFIX_LEN, myLength1 - LAT_PREFIX_LEN );
lat2Str = theProj4String.mid( myStart2 + LAT_PREFIX_LEN, myLength2 - LAT_PREFIX_LEN );
}
// If we found the lat_1 and lat_2 we need to swap and check to see if we can find it...
if ( lat1Str != "" && lat2Str != "" )
{
// Make our new string to check...
QString theProj4StringModified = theProj4String;
// First just swap in the lat_2 value for lat_1 value
theProj4StringModified.replace( myStart1 + LAT_PREFIX_LEN, myLength1 - LAT_PREFIX_LEN, lat2Str );
// Now we have to find the lat_2 location again since it has potentially moved...
myStart2 = 0;
myStart2 = myLat2RegExp.indexIn( theProj4String, myStart2 );
theProj4StringModified.replace( myStart2 + LAT_PREFIX_LEN, myLength2 - LAT_PREFIX_LEN, lat1Str );
QgsDebugMsg( "trying proj4string match with swapped lat_1,lat_2" );
myRecord = getRecord( "select * from tbl_srs where parameters=" + quotedValue( theProj4StringModified.trimmed() ) + " order by deprecated" );
}
}
if ( myRecord.empty() )
{
// match all parameters individually:
// - order of parameters doesn't matter
// - found definition may have more parameters (like +towgs84 in GDAL)
// - retry without datum, if no match is found (looks like +datum<>WGS84 was dropped in GDAL)
QString sql = "SELECT * FROM tbl_srs WHERE ";
QString delim = "";
QString datum;
// split on spaces followed by a plus sign (+) to deal
// also with parameters containing spaces (e.g. +nadgrids)
foreach( QString param, theProj4String.split( QRegExp( "\\s+(?=\\+)" ), QString::SkipEmptyParts ) )
{
QString arg = QString( "' '||parameters||' ' LIKE %1" ).arg( quotedValue( QString( "% %1 %" ).arg( param ) ) );
if ( param.startsWith( "+datum=" ) )
{
datum = arg;
}
else
{
sql += delim + arg;
delim = " AND ";
}
}
if ( !datum.isEmpty() )
{
myRecord = getRecord( sql + delim + datum + " order by deprecated" );
}
if ( myRecord.empty() )
{
// datum might have disappeared in definition - retry without it
myRecord = getRecord( sql + " order by deprecated" );
}
}
if ( !myRecord.empty() )
{
mySrsId = myRecord["srs_id"].toLong();
QgsDebugMsg( "proj4string param match search for srsid returned srsid: " + QString::number( mySrsId ) );
if ( mySrsId > 0 )
{
createFromSrsId( mySrsId );
}
}
else
{
// Last ditch attempt to piece together what we know of the projection to find a match...
QgsDebugMsg( "globbing search for srsid from this proj string" );
setProj4String( theProj4String );
mySrsId = findMatchingProj();
QgsDebugMsg( "globbing search for srsid returned srsid: " + QString::number( mySrsId ) );
if ( mySrsId > 0 )
{
createFromSrsId( mySrsId );
}
else
{
mIsValidFlag = false;
}
}
// if we failed to look up the projection in database, don't worry. we can still use it :)
if ( !mIsValidFlag )
{
QgsDebugMsg( "Projection is not found in databases." );
setProj4String( theProj4String );
// Is the SRS is valid now, we know it's a decent +proj string that can be entered into the srs.db
if ( mIsValidFlag )
{
// but the proj.4 parsed string might already be in our database
myRecord = getRecord( "select * from tbl_srs where parameters=" + quotedValue( toProj4() ) + " order by deprecated" );
if ( myRecord.empty() )
{
// It's not, so try to add it
QgsDebugMsg( "Projection appears to be valid. Save to database!" );
mIsValidFlag = saveAsUserCRS();
if ( mIsValidFlag )
{
// but validate that it's there afterwards
myRecord = getRecord( "select * from tbl_srs where parameters=" + quotedValue( toProj4() ) + " order by deprecated" );
}
}
if ( !myRecord.empty() )
{
// take the srid from the record
mySrsId = myRecord["srs_id"].toLong();
QgsDebugMsg( "proj4string match search for srsid returned srsid: " + QString::number( mySrsId ) );
if ( mySrsId > 0 )
{
createFromSrsId( mySrsId );
}
else
{
QgsDebugMsg( QString( "invalid srid %1 found" ).arg( mySrsId ) );
mIsValidFlag = false;
}
}
else
{
QgsDebugMsg( "Couldn't find newly added proj string?" );
mIsValidFlag = false;
}
}
}
return mIsValidFlag;
}
//private method meant for internal use by this class only
QgsCoordinateReferenceSystem::RecordMap QgsCoordinateReferenceSystem::getRecord( QString theSql )
{
QString myDatabaseFileName;
QgsCoordinateReferenceSystem::RecordMap myMap;
QString myFieldName;
QString myFieldValue;
sqlite3 *myDatabase;
const char *myTail;
sqlite3_stmt *myPreparedStatement;
int myResult;
QgsDebugMsg( "running query: " + theSql );
// Get the full path name to the sqlite3 spatial reference database.
myDatabaseFileName = QgsApplication::srsDbFilePath();
QFileInfo myInfo( myDatabaseFileName );
if ( !myInfo.exists() )
{
QgsDebugMsg( "failed : " + myDatabaseFileName +
" does not exist!" );
return myMap;
}
//check the db is available
myResult = openDb( myDatabaseFileName, &myDatabase );
if ( myResult != SQLITE_OK )
{
return myMap;
}
myResult = sqlite3_prepare( myDatabase, theSql.toUtf8(), theSql.toUtf8().length(), &myPreparedStatement, &myTail );
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK && sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
{
QgsDebugMsg( "trying system srs.db" );
int myColumnCount = sqlite3_column_count( myPreparedStatement );
//loop through each column in the record adding its expression name and value to the map
for ( int myColNo = 0; myColNo < myColumnCount; myColNo++ )
{
myFieldName = QString::fromUtf8(( char * )sqlite3_column_name( myPreparedStatement, myColNo ) );
myFieldValue = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, myColNo ) );
myMap[myFieldName] = myFieldValue;
}
}
else
{
QgsDebugMsg( "trying user qgis.db" );
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
myDatabaseFileName = QgsApplication::qgisUserDbFilePath();
QFileInfo myFileInfo;
myFileInfo.setFile( myDatabaseFileName );
if ( !myFileInfo.exists( ) )
{
QgsDebugMsg( "user qgis.db not found" );
return myMap;
}
//check the db is available
myResult = openDb( myDatabaseFileName, &myDatabase );
if ( myResult != SQLITE_OK )
{
return myMap;
}
myResult = sqlite3_prepare( myDatabase, theSql.toUtf8(), theSql.toUtf8().length(), &myPreparedStatement, &myTail );
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK && sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
{
int myColumnCount = sqlite3_column_count( myPreparedStatement );
//loop through each column in the record adding its field name and value to the map
for ( int myColNo = 0; myColNo < myColumnCount; myColNo++ )
{
myFieldName = QString::fromUtf8(( char * )sqlite3_column_name( myPreparedStatement, myColNo ) );
myFieldValue = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, myColNo ) );
myMap[myFieldName] = myFieldValue;
}
}
else
{
QgsDebugMsg( "failed : " + theSql );
}
}
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
#ifdef QGISDEBUG
QgsDebugMsg( "retrieved: " + theSql );
RecordMap::Iterator it;
for ( it = myMap.begin(); it != myMap.end(); ++it )
{
QgsDebugMsgLevel( it.key() + " => " + it.value(), 2 );
}
#endif
return myMap;
}
// Accessors -----------------------------------
long QgsCoordinateReferenceSystem::srsid() const
{
return mSrsId;
}
long QgsCoordinateReferenceSystem::postgisSrid() const
{
return mSRID;
}
long QgsCoordinateReferenceSystem::epsg() const
{
if ( mAuthId.startsWith( "EPSG:", Qt::CaseInsensitive ) )
return mAuthId.mid( 5 ).toLong();
else
return 0;
}
QString QgsCoordinateReferenceSystem::authid() const
{
return mAuthId;
}
QString QgsCoordinateReferenceSystem::description() const
{
if ( mDescription.isNull() )
{
return "";
}
else
{
return mDescription;
}
}
QString QgsCoordinateReferenceSystem::projectionAcronym() const
{
if ( mProjectionAcronym.isNull() )
{
return "";
}
else
{
return mProjectionAcronym;
}
}
QString QgsCoordinateReferenceSystem::ellipsoidAcronym() const
{
if ( mEllipsoidAcronym.isNull() )
{
return "";
}
else
{
return mEllipsoidAcronym;
}
}
QString QgsCoordinateReferenceSystem::toProj4() const
{
if ( !mIsValidFlag )
return "";
QString toProj4;
char *proj4src = NULL;
OSRExportToProj4( mCRS, &proj4src );
toProj4 = proj4src;
CPLFree( proj4src );
// Stray spaces at the end?
return toProj4.trimmed();
}
bool QgsCoordinateReferenceSystem::geographicFlag() const
{
return mGeoFlag;
}
QGis::UnitType QgsCoordinateReferenceSystem::mapUnits() const
{
return mMapUnits;
}
// Mutators -----------------------------------
void QgsCoordinateReferenceSystem::setInternalId( long theSrsId )
{
mSrsId = theSrsId;
}
void QgsCoordinateReferenceSystem::setAuthId( QString authId )
{
mAuthId = authId;
}
void QgsCoordinateReferenceSystem::setSrid( long theSrid )
{
mSRID = theSrid;
}
void QgsCoordinateReferenceSystem::setDescription( QString theDescription )
{
mDescription = theDescription;
}
void QgsCoordinateReferenceSystem::setProj4String( QString theProj4String )
{
const char *oldlocale = setlocale( LC_NUMERIC, NULL );
setlocale( LC_NUMERIC, "C" );
OSRDestroySpatialReference( mCRS );
mCRS = OSRNewSpatialReference( NULL );
mIsValidFlag = OSRImportFromProj4( mCRS, theProj4String.toLatin1().constData() ) == OGRERR_NONE;
mWkt.clear();
setMapUnits();
#if defined(QGISDEBUG) && QGISDEBUG>=3
debugPrint();
#endif
setlocale( LC_NUMERIC, oldlocale );
}
void QgsCoordinateReferenceSystem::setGeographicFlag( bool theGeoFlag )
{
mGeoFlag = theGeoFlag;
}
void QgsCoordinateReferenceSystem::setEpsg( long theEpsg )
{
mAuthId = QString( "EPSG:%1" ).arg( theEpsg );
}
void QgsCoordinateReferenceSystem::setProjectionAcronym( QString theProjectionAcronym )
{
mProjectionAcronym = theProjectionAcronym;
}
void QgsCoordinateReferenceSystem::setEllipsoidAcronym( QString theEllipsoidAcronym )
{
mEllipsoidAcronym = theEllipsoidAcronym;
}
void QgsCoordinateReferenceSystem::setMapUnits()
{
if ( !mIsValidFlag )
{
mMapUnits = QGis::UnknownUnit;
return;
}
char *unitName;
// Of interest to us is that this call adds in a unit parameter if
// one doesn't already exist.
OSRFixup( mCRS );
if ( OSRIsProjected( mCRS ) )
{
double toMeter = OSRGetLinearUnits( mCRS, &unitName );
QString unit( unitName );
// If the units parameter was created during the Fixup() call
// above, the name of the units is likely to be 'unknown'. Try to
// do better than that ... (but perhaps ogr should be enhanced to
// do this instead?).
static const double feetToMeter = 0.3048;
static const double smallNum = 1e-3;
if ( qAbs( toMeter - feetToMeter ) < smallNum )
unit = "Foot";
QgsDebugMsg( "Projection has linear units of " + unit );
if ( doubleNear( toMeter, 1.0 ) ) //Unit name for meters would be "metre"
mMapUnits = QGis::Meters;
else if ( unit == "Foot" )
mMapUnits = QGis::Feet;
else
{
QgsDebugMsg( "Unsupported map units of " + unit );
mMapUnits = QGis::UnknownUnit;
}
}
else
{
OSRGetAngularUnits( mCRS, &unitName );
QString unit( unitName );
if ( unit == "degree" )
mMapUnits = QGis::Degrees;
else
{
QgsDebugMsg( "Unsupported map units of " + unit );
mMapUnits = QGis::UnknownUnit;
}
QgsDebugMsgLevel( "Projection has angular units of " + unit, 3 );
}
}
/*
* check if srs is a geocs or a proj cs (using ogr isGeographic)
* then sequentially walk through the database (first users qgis.db srs tbl then
* system srs.db tbl), converting each entry into an ogr srs and using isSame
* or isSameGeocs (essentially calling the == overloaded operator). We'll try to
* be smart about this and first parse out the proj and ellpse strings and only
* check for a match in entities that have the same ellps and proj entries so
* that it doesnt munch yer cpu so much.
*/
long QgsCoordinateReferenceSystem::findMatchingProj()
{
QgsDebugMsg( "entered." );
if ( mEllipsoidAcronym.isNull() || mProjectionAcronym.isNull() || !mIsValidFlag )
{
QgsDebugMsg( "QgsCoordinateReferenceSystem::findMatchingProj will only work if prj acr ellipsoid acr and proj4string are set"
" and the current projection is valid!" );
return 0;
}
sqlite3 *myDatabase;
const char *myTail;
sqlite3_stmt *myPreparedStatement;
int myResult;
// Set up the query to retrieve the projection information needed to populate the list
QString mySql = QString( "select srs_id,parameters from tbl_srs where projection_acronym=%1 and ellipsoid_acronym=%2 order by deprecated" )
.arg( quotedValue( mProjectionAcronym ) )
.arg( quotedValue( mEllipsoidAcronym ) );
// Get the full path name to the sqlite3 spatial reference database.
QString myDatabaseFileName = QgsApplication::srsDbFilePath();
//check the db is available
myResult = openDb( myDatabaseFileName, &myDatabase );
if ( myResult != SQLITE_OK )
{
return 0;
}
myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK )
{
while ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
{
QString mySrsId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
QString myProj4String = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 1 ) );
if ( equals( myProj4String ) )
{
QgsDebugMsg( "-------> MATCH FOUND in srs.db srsid: " + mySrsId );
// close the sqlite3 statement
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
return mySrsId.toLong();
}
else
{
// QgsDebugMsg(QString(" Not matched : %1").arg(myProj4String));
}
}
}
QgsDebugMsg( "no match found in srs.db, trying user db now!" );
// close the sqlite3 statement
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
//
// Try the users db now
//
myDatabaseFileName = QgsApplication::qgisUserDbFilePath();
//check the db is available
myResult = openDb( myDatabaseFileName, &myDatabase );
if ( myResult != SQLITE_OK )
{
return 0;
}
myResult = sqlite3_prepare( myDatabase, mySql.toUtf8(), mySql.toUtf8().length(), &myPreparedStatement, &myTail );
// XXX Need to free memory from the error msg if one is set
if ( myResult == SQLITE_OK )
{
while ( sqlite3_step( myPreparedStatement ) == SQLITE_ROW )
{
QString mySrsId = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 0 ) );
QString myProj4String = QString::fromUtf8(( char * )sqlite3_column_text( myPreparedStatement, 1 ) );
if ( equals( myProj4String ) )
{
QgsDebugMsg( "-------> MATCH FOUND in user qgis.db srsid: " + mySrsId );
// close the sqlite3 statement
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
return mySrsId.toLong();
}
else
{
// QgsDebugMsg(QString(" Not matched : %1").arg(myProj4String));
}
}
}
QgsDebugMsg( "no match found in user db" );
// close the sqlite3 statement
sqlite3_finalize( myPreparedStatement );
sqlite3_close( myDatabase );
return 0;
}
bool QgsCoordinateReferenceSystem::operator==( const QgsCoordinateReferenceSystem &theSrs ) const