QGIS API Documentation 4.0.0-Norrköping (1ddcee3d0e4)
Loading...
Searching...
No Matches
qgsgooglemapsgeocoder.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsgooglemapsgeocoder.cpp
3 ---------------
4 Date : November 2020
5 Copyright : (C) 2020 by Nyall Dawson
6 Email : nyall dot dawson 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
17
20#include "qgsgeocodercontext.h"
21#include "qgslogger.h"
23#include "qgsreadwritelocker.h"
25
26#include <QCryptographicHash>
27#include <QJsonDocument>
28#include <QJsonObject>
29#include <QNetworkRequest>
30#include <QString>
31#include <QUrl>
32#include <QUrlQuery>
33
34using namespace Qt::StringLiterals;
35
36QReadWriteLock QgsGoogleMapsGeocoder::sMutex;
37
38typedef QMap< QUrl, QList< QgsGeocoderResult > > CachedGeocodeResult;
39Q_GLOBAL_STATIC( CachedGeocodeResult, sCachedResultsGM )
40
41
42QgsGoogleMapsGeocoder::QgsGoogleMapsGeocoder( const QString &apiKey, const QString &regionBias )
44 , mApiKey( apiKey )
45 , mRegion( regionBias )
46 , mEndpoint( u"https://maps.googleapis.com/maps/api/geocode/json"_s )
47{}
48
53
55{
56 QgsFields fields;
57 fields.append( QgsField( u"location_type"_s, QMetaType::Type::QString ) );
58 fields.append( QgsField( u"formatted_address"_s, QMetaType::Type::QString ) );
59 fields.append( QgsField( u"place_id"_s, QMetaType::Type::QString ) );
60
61 // add more?
62 fields.append( QgsField( u"street_number"_s, QMetaType::Type::QString ) );
63 fields.append( QgsField( u"route"_s, QMetaType::Type::QString ) );
64 fields.append( QgsField( u"locality"_s, QMetaType::Type::QString ) );
65 fields.append( QgsField( u"administrative_area_level_2"_s, QMetaType::Type::QString ) );
66 fields.append( QgsField( u"administrative_area_level_1"_s, QMetaType::Type::QString ) );
67 fields.append( QgsField( u"country"_s, QMetaType::Type::QString ) );
68 fields.append( QgsField( u"postal_code"_s, QMetaType::Type::QString ) );
69 return fields;
70}
71
76
77QList<QgsGeocoderResult> QgsGoogleMapsGeocoder::geocodeString( const QString &string, const QgsGeocoderContext &context, QgsFeedback *feedback ) const
78{
79 QgsRectangle bounds;
80 if ( !context.areaOfInterest().isEmpty() )
81 {
82 QgsGeometry g = context.areaOfInterest();
83 const QgsCoordinateTransform ct( context.areaOfInterestCrs(), QgsCoordinateReferenceSystem( u"EPSG:4326"_s ), context.transformContext() );
84 try
85 {
86 g.transform( ct );
87 bounds = g.boundingBox();
88 }
89 catch ( QgsCsException & )
90 {
91 QgsDebugError( "Could not transform geocode bounds to WGS84" );
92 }
93 }
94
95 const QUrl url = requestUrl( string, bounds );
96
98 const auto it = sCachedResultsGM()->constFind( url );
99 if ( it != sCachedResultsGM()->constEnd() )
100 {
101 return *it;
102 }
103 locker.unlock();
104
105 QNetworkRequest request( url );
106 QgsSetRequestInitiatorClass( request, u"QgsGoogleMapsGeocoder"_s );
107
109 const QgsBlockingNetworkRequest::ErrorCode errorCode = newReq.get( request, false, feedback );
110 if ( errorCode != QgsBlockingNetworkRequest::NoError )
111 {
112 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( newReq.errorMessage() );
113 }
114
115 // Parse data
116 QJsonParseError err;
117 const QJsonDocument doc = QJsonDocument::fromJson( newReq.reply().content(), &err );
118 if ( doc.isNull() )
119 {
120 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( err.errorString() );
121 }
122 const QVariantMap res = doc.object().toVariantMap();
123 const QString status = res.value( u"status"_s ).toString();
124 if ( status.isEmpty() || !res.contains( u"results"_s ) )
125 {
126 return QList<QgsGeocoderResult>();
127 }
128
129 if ( res.contains( "error_message"_L1 ) )
130 {
131 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( res.value( u"error_message"_s ).toString() );
132 }
133
134 if ( status == "REQUEST_DENIED"_L1 || status == "OVER_QUERY_LIMIT"_L1 )
135 {
136 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( QObject::tr( "Request denied -- the API key was rejected" ) );
137 }
138 if ( status != "OK"_L1 && status != "ZERO_RESULTS"_L1 )
139 {
140 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( res.value( u"status"_s ).toString() );
141 }
142
143 // all good!
145
146 const QVariantList results = res.value( u"results"_s ).toList();
147 if ( results.empty() )
148 {
149 sCachedResultsGM()->insert( url, QList<QgsGeocoderResult>() );
150 return QList<QgsGeocoderResult>();
151 }
152
153 QList< QgsGeocoderResult > matches;
154 matches.reserve( results.size() );
155 for ( const QVariant &result : results )
156 {
157 matches << jsonToResult( result.toMap() );
158 }
159 sCachedResultsGM()->insert( url, matches );
160
161 return matches;
162}
163
164QUrl QgsGoogleMapsGeocoder::requestUrl( const QString &address, const QgsRectangle &bounds ) const
165{
166 QUrl res( mEndpoint );
167 QUrlQuery query;
168 if ( !bounds.isNull() )
169 {
170 query.addQueryItem( u"bounds"_s, u"%1,%2|%3,%4"_s.arg( bounds.yMinimum() ).arg( bounds.xMinimum() ).arg( bounds.yMaximum() ).arg( bounds.yMinimum() ) );
171 }
172 if ( !mRegion.isEmpty() )
173 {
174 query.addQueryItem( u"region"_s, mRegion.toLower() );
175 }
176 query.addQueryItem( u"sensor"_s, u"false"_s );
177 query.addQueryItem( u"address"_s, address );
178 query.addQueryItem( u"key"_s, mApiKey );
179 res.setQuery( query );
180
181
182 if ( res.toString().contains( "fake_qgis_http_endpoint"_L1 ) )
183 {
184 // Just for testing with local files instead of http:// resources
185 QString modifiedUrlString = res.toString();
186 // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
187 modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
188 modifiedUrlString.replace( "fake_qgis_http_endpoint/"_L1, "fake_qgis_http_endpoint_"_L1 );
189 QgsDebugMsgLevel( u"Get %1"_s.arg( modifiedUrlString ), 2 );
190 modifiedUrlString = modifiedUrlString.mid( u"http://"_s.size() );
191 QString args = modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) );
192 if ( modifiedUrlString.size() > 150 )
193 {
194 args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
195 }
196 else
197 {
198 args.replace( "?"_L1, "_"_L1 );
199 args.replace( "&"_L1, "_"_L1 );
200 args.replace( "<"_L1, "_"_L1 );
201 args.replace( ">"_L1, "_"_L1 );
202 args.replace( "'"_L1, "_"_L1 );
203 args.replace( "\""_L1, "_"_L1 );
204 args.replace( " "_L1, "_"_L1 );
205 args.replace( ":"_L1, "_"_L1 );
206 args.replace( "/"_L1, "_"_L1 );
207 args.replace( "\n"_L1, "_"_L1 );
208 }
209#ifdef Q_OS_WIN
210 // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
211 // so we must restore it
212 if ( modifiedUrlString[1] == '/' )
213 {
214 modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
215 }
216#endif
217 modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
218 QgsDebugMsgLevel( u"Get %1 (after laundering)"_s.arg( modifiedUrlString ), 2 );
219 res = QUrl::fromLocalFile( modifiedUrlString );
220 }
221
222 return res;
223}
224
226{
227 const QVariantMap geometry = json.value( u"geometry"_s ).toMap();
228 const QVariantMap location = geometry.value( u"location"_s ).toMap();
229 const double latitude = location.value( u"lat"_s ).toDouble();
230 const double longitude = location.value( u"lng"_s ).toDouble();
231
232 const QgsGeometry geom = QgsGeometry::fromPointXY( QgsPointXY( longitude, latitude ) );
233
234 QgsGeocoderResult res( json.value( u"formatted_address"_s ).toString(), geom, QgsCoordinateReferenceSystem( u"EPSG:4326"_s ) );
235
236 QVariantMap attributes;
237
238 if ( json.contains( u"formatted_address"_s ) )
239 attributes.insert( u"formatted_address"_s, json.value( u"formatted_address"_s ).toString() );
240 if ( json.contains( u"place_id"_s ) )
241 attributes.insert( u"place_id"_s, json.value( u"place_id"_s ).toString() );
242 if ( geometry.contains( u"location_type"_s ) )
243 attributes.insert( u"location_type"_s, geometry.value( u"location_type"_s ).toString() );
244
245 const QVariantList components = json.value( u"address_components"_s ).toList();
246 for ( const QVariant &component : components )
247 {
248 const QVariantMap componentMap = component.toMap();
249 const QStringList types = componentMap.value( u"types"_s ).toStringList();
250
251 for ( const QString &t : { u"street_number"_s, u"route"_s, u"locality"_s, u"administrative_area_level_2"_s, u"administrative_area_level_1"_s, u"country"_s, u"postal_code"_s } )
252 {
253 if ( types.contains( t ) )
254 {
255 attributes.insert( t, componentMap.value( u"long_name"_s ).toString() );
256 if ( t == "administrative_area_level_1"_L1 )
257 res.setGroup( componentMap.value( u"long_name"_s ).toString() );
258 }
259 }
260 }
261
262 if ( geometry.contains( u"viewport"_s ) )
263 {
264 const QVariantMap viewport = geometry.value( u"viewport"_s ).toMap();
265 const QVariantMap northEast = viewport.value( u"northeast"_s ).toMap();
266 const QVariantMap southWest = viewport.value( u"southwest"_s ).toMap();
267 res.setViewport( QgsRectangle( southWest.value( u"lng"_s ).toDouble(), southWest.value( u"lat"_s ).toDouble(), northEast.value( u"lng"_s ).toDouble(), northEast.value( u"lat"_s ).toDouble() ) );
268 }
269
270 res.setAdditionalAttributes( attributes );
271 return res;
272}
273
274void QgsGoogleMapsGeocoder::setEndpoint( const QString &endpoint )
275{
276 mEndpoint = endpoint;
277}
278
280{
281 return mApiKey;
282}
283
285{
286 mApiKey = apiKey;
287}
288
290{
291 return mRegion;
292}
293
295{
296 mRegion = region;
297}
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:294
@ Point
Point.
Definition qgis.h:296
A thread safe class for performing blocking (sync) network requests, with full support for QGIS proxy...
QString errorMessage() const
Returns the error message string, after a get(), post(), head() or put() request has been made.
ErrorCode get(QNetworkRequest &request, bool forceRefresh=false, QgsFeedback *feedback=nullptr, RequestFlags requestFlags=QgsBlockingNetworkRequest::RequestFlags())
Performs a "get" operation on the specified request.
@ NoError
No error was encountered.
QgsNetworkReplyContent reply() const
Returns the content of the network reply, after a get(), post(), head() or put() request has been mad...
Represents a coordinate reference system (CRS).
Handles coordinate transforms between two coordinate systems.
Custom exception class for Coordinate Reference System related exceptions.
Base class for feedback objects to be used for cancellation of something running in a worker thread.
Definition qgsfeedback.h:44
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:56
Container of fields for a vector layer.
Definition qgsfields.h:46
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
Definition qgsfields.cpp:75
Encapsulates the context of a geocoding operation.
QgsCoordinateTransformContext transformContext() const
Returns the coordinate transform context, which should be used whenever the geocoder constructs a coo...
QgsCoordinateReferenceSystem areaOfInterestCrs() const
Returns the coordinate reference system for the area of interest, which can be used to indicate the d...
QgsGeometry areaOfInterest() const
Returns the optional area of interest, which can be used to indicate the desired geographic area wher...
Interface for geocoders.
Definition qgsgeocoder.h:37
@ GeocodesStrings
Can geocode string input values.
Definition qgsgeocoder.h:42
QFlags< Flag > Flags
Definition qgsgeocoder.h:45
Represents a matching result from a geocoder search.
void setAdditionalAttributes(const QVariantMap &attributes)
Setss additional attributes generated during the geocode, which may be added to features being geocod...
void setGroup(const QString &group)
Sets the optional group value for the result.
void setViewport(const QgsRectangle &viewport)
Sets the suggested viewport for the result, which reflects a recommended map extent for displaying th...
static QgsGeocoderResult errorResult(const QString &errorMessage)
Creates an invalid error result, with the specified errorMessage string.
A geometry is the spatial representation of a feature.
Qgis::GeometryOperationResult transform(const QgsCoordinateTransform &ct, Qgis::TransformDirection direction=Qgis::TransformDirection::Forward, bool transformZ=false)
Transforms this geometry as described by the coordinate transform ct.
static QgsGeometry fromPointXY(const QgsPointXY &point)
Creates a new geometry from a QgsPointXY object.
bool isEmpty() const
Returns true if the geometry is empty (eg a linestring with no vertices, or a collection with no geom...
QgsRectangle boundingBox() const
Returns the bounding box of the geometry.
QList< QgsGeocoderResult > geocodeString(const QString &string, const QgsGeocoderContext &context, QgsFeedback *feedback=nullptr) const override
Geocodes a string.
void setEndpoint(const QString &endpoint)
Sets a specific API endpoint to use for requests.
QgsGeocoderResult jsonToResult(const QVariantMap &json) const
Converts a JSON result returned from the Google Maps service to a geocoder result object.
QgsFields appendedFields() const override
Returns a set of newly created fields which will be appended to existing features during the geocode ...
QString apiKey() const
Returns the API key which will be used when accessing the Google Maps API.
Qgis::WkbType wkbType() const override
Returns the WKB type of geometries returned by the geocoder.
QString region() const
Returns the optional region bias which will be used to prioritize results in a certain region.
QUrl requestUrl(const QString &address, const QgsRectangle &bounds=QgsRectangle()) const
Returns the URL generated for geocoding the specified address.
QgsGoogleMapsGeocoder(const QString &apiKey, const QString &regionBias=QString())
Constructor for QgsGoogleMapsGeocoder.
void setRegion(const QString &region)
Sets the optional region bias which will be used to prioritize results in a certain region.
void setApiKey(const QString &key)
Sets the API key to use when accessing the Google Maps API.
Flags flags() const override
Returns the geocoder's capability flags.
QByteArray content() const
Returns the reply content.
Represents a 2D point.
Definition qgspointxy.h:62
A convenience class that simplifies locking and unlocking QReadWriteLocks.
@ Write
Lock for write.
void unlock()
Unlocks the lock.
void changeMode(Mode mode)
Change the mode of the lock to mode.
A rectangle specified with double values.
double xMinimum
double yMinimum
double yMaximum
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
QMap< QUrl, QList< QgsGeocoderResult > > CachedGeocodeResult
#define QgsDebugMsgLevel(str, level)
Definition qgslogger.h:63
#define QgsDebugError(str)
Definition qgslogger.h:59
#define QgsSetRequestInitiatorClass(request, _class)