QGIS API Documentation 3.99.0-Master (e9821da5c6b)
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
49}
50
55
57{
58 QgsFields fields;
59 fields.append( QgsField( u"location_type"_s, QMetaType::Type::QString ) );
60 fields.append( QgsField( u"formatted_address"_s, QMetaType::Type::QString ) );
61 fields.append( QgsField( u"place_id"_s, QMetaType::Type::QString ) );
62
63 // add more?
64 fields.append( QgsField( u"street_number"_s, QMetaType::Type::QString ) );
65 fields.append( QgsField( u"route"_s, QMetaType::Type::QString ) );
66 fields.append( QgsField( u"locality"_s, QMetaType::Type::QString ) );
67 fields.append( QgsField( u"administrative_area_level_2"_s, QMetaType::Type::QString ) );
68 fields.append( QgsField( u"administrative_area_level_1"_s, QMetaType::Type::QString ) );
69 fields.append( QgsField( u"country"_s, QMetaType::Type::QString ) );
70 fields.append( QgsField( u"postal_code"_s, QMetaType::Type::QString ) );
71 return fields;
72}
73
78
79QList<QgsGeocoderResult> QgsGoogleMapsGeocoder::geocodeString( const QString &string, const QgsGeocoderContext &context, QgsFeedback *feedback ) const
80{
81 QgsRectangle bounds;
82 if ( !context.areaOfInterest().isEmpty() )
83 {
84 QgsGeometry g = context.areaOfInterest();
85 const QgsCoordinateTransform ct( context.areaOfInterestCrs(), QgsCoordinateReferenceSystem( u"EPSG:4326"_s ), context.transformContext() );
86 try
87 {
88 g.transform( ct );
89 bounds = g.boundingBox();
90 }
91 catch ( QgsCsException & )
92 {
93 QgsDebugError( "Could not transform geocode bounds to WGS84" );
94 }
95 }
96
97 const QUrl url = requestUrl( string, bounds );
98
100 const auto it = sCachedResultsGM()->constFind( url );
101 if ( it != sCachedResultsGM()->constEnd() )
102 {
103 return *it;
104 }
105 locker.unlock();
106
107 QNetworkRequest request( url );
108 QgsSetRequestInitiatorClass( request, u"QgsGoogleMapsGeocoder"_s );
109
111 const QgsBlockingNetworkRequest::ErrorCode errorCode = newReq.get( request, false, feedback );
112 if ( errorCode != QgsBlockingNetworkRequest::NoError )
113 {
114 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( newReq.errorMessage() );
115 }
116
117 // Parse data
118 QJsonParseError err;
119 const QJsonDocument doc = QJsonDocument::fromJson( newReq.reply().content(), &err );
120 if ( doc.isNull() )
121 {
122 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( err.errorString() );
123 }
124 const QVariantMap res = doc.object().toVariantMap();
125 const QString status = res.value( u"status"_s ).toString();
126 if ( status.isEmpty() || !res.contains( u"results"_s ) )
127 {
128 return QList<QgsGeocoderResult>();
129 }
130
131 if ( res.contains( "error_message"_L1 ) )
132 {
133 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( res.value( u"error_message"_s ).toString() );
134 }
135
136 if ( status == "REQUEST_DENIED"_L1 || status == "OVER_QUERY_LIMIT"_L1 )
137 {
138 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( QObject::tr( "Request denied -- the API key was rejected" ) );
139 }
140 if ( status != "OK"_L1 && status != "ZERO_RESULTS"_L1 )
141 {
142 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( res.value( u"status"_s ).toString() );
143 }
144
145 // all good!
147
148 const QVariantList results = res.value( u"results"_s ).toList();
149 if ( results.empty() )
150 {
151 sCachedResultsGM()->insert( url, QList<QgsGeocoderResult>() );
152 return QList<QgsGeocoderResult>();
153 }
154
155 QList< QgsGeocoderResult > matches;
156 matches.reserve( results.size( ) );
157 for ( const QVariant &result : results )
158 {
159 matches << jsonToResult( result.toMap() );
160 }
161 sCachedResultsGM()->insert( url, matches );
162
163 return matches;
164}
165
166QUrl QgsGoogleMapsGeocoder::requestUrl( const QString &address, const QgsRectangle &bounds ) const
167{
168 QUrl res( mEndpoint );
169 QUrlQuery query;
170 if ( !bounds.isNull() )
171 {
172 query.addQueryItem( u"bounds"_s, u"%1,%2|%3,%4"_s.arg( bounds.yMinimum() )
173 .arg( bounds.xMinimum() )
174 .arg( bounds.yMaximum() )
175 .arg( bounds.yMinimum() ) );
176 }
177 if ( !mRegion.isEmpty() )
178 {
179 query.addQueryItem( u"region"_s, mRegion.toLower() );
180 }
181 query.addQueryItem( u"sensor"_s, u"false"_s );
182 query.addQueryItem( u"address"_s, address );
183 query.addQueryItem( u"key"_s, mApiKey );
184 res.setQuery( query );
185
186
187 if ( res.toString().contains( "fake_qgis_http_endpoint"_L1 ) )
188 {
189 // Just for testing with local files instead of http:// resources
190 QString modifiedUrlString = res.toString();
191 // Qt5 does URL encoding from some reason (of the FILTER parameter for example)
192 modifiedUrlString = QUrl::fromPercentEncoding( modifiedUrlString.toUtf8() );
193 modifiedUrlString.replace( "fake_qgis_http_endpoint/"_L1, "fake_qgis_http_endpoint_"_L1 );
194 QgsDebugMsgLevel( u"Get %1"_s.arg( modifiedUrlString ), 2 );
195 modifiedUrlString = modifiedUrlString.mid( u"http://"_s.size() );
196 QString args = modifiedUrlString.mid( modifiedUrlString.indexOf( '?' ) );
197 if ( modifiedUrlString.size() > 150 )
198 {
199 args = QCryptographicHash::hash( args.toUtf8(), QCryptographicHash::Md5 ).toHex();
200 }
201 else
202 {
203 args.replace( "?"_L1, "_"_L1 );
204 args.replace( "&"_L1, "_"_L1 );
205 args.replace( "<"_L1, "_"_L1 );
206 args.replace( ">"_L1, "_"_L1 );
207 args.replace( "'"_L1, "_"_L1 );
208 args.replace( "\""_L1, "_"_L1 );
209 args.replace( " "_L1, "_"_L1 );
210 args.replace( ":"_L1, "_"_L1 );
211 args.replace( "/"_L1, "_"_L1 );
212 args.replace( "\n"_L1, "_"_L1 );
213 }
214#ifdef Q_OS_WIN
215 // Passing "urls" like "http://c:/path" to QUrl 'eats' the : after c,
216 // so we must restore it
217 if ( modifiedUrlString[1] == '/' )
218 {
219 modifiedUrlString = modifiedUrlString[0] + ":/" + modifiedUrlString.mid( 2 );
220 }
221#endif
222 modifiedUrlString = modifiedUrlString.mid( 0, modifiedUrlString.indexOf( '?' ) ) + args;
223 QgsDebugMsgLevel( u"Get %1 (after laundering)"_s.arg( modifiedUrlString ), 2 );
224 res = QUrl::fromLocalFile( modifiedUrlString );
225 }
226
227 return res;
228}
229
231{
232 const QVariantMap geometry = json.value( u"geometry"_s ).toMap();
233 const QVariantMap location = geometry.value( u"location"_s ).toMap();
234 const double latitude = location.value( u"lat"_s ).toDouble();
235 const double longitude = location.value( u"lng"_s ).toDouble();
236
237 const QgsGeometry geom = QgsGeometry::fromPointXY( QgsPointXY( longitude, latitude ) );
238
239 QgsGeocoderResult res( json.value( u"formatted_address"_s ).toString(),
240 geom,
241 QgsCoordinateReferenceSystem( u"EPSG:4326"_s ) );
242
243 QVariantMap attributes;
244
245 if ( json.contains( u"formatted_address"_s ) )
246 attributes.insert( u"formatted_address"_s, json.value( u"formatted_address"_s ).toString() );
247 if ( json.contains( u"place_id"_s ) )
248 attributes.insert( u"place_id"_s, json.value( u"place_id"_s ).toString() );
249 if ( geometry.contains( u"location_type"_s ) )
250 attributes.insert( u"location_type"_s, geometry.value( u"location_type"_s ).toString() );
251
252 const QVariantList components = json.value( u"address_components"_s ).toList();
253 for ( const QVariant &component : components )
254 {
255 const QVariantMap componentMap = component.toMap();
256 const QStringList types = componentMap.value( u"types"_s ).toStringList();
257
258 for ( const QString &t :
259 {
260 u"street_number"_s,
261 u"route"_s,
262 u"locality"_s,
263 u"administrative_area_level_2"_s,
264 u"administrative_area_level_1"_s,
265 u"country"_s,
266 u"postal_code"_s
267 } )
268 {
269 if ( types.contains( t ) )
270 {
271 attributes.insert( t, componentMap.value( u"long_name"_s ).toString() );
272 if ( t == "administrative_area_level_1"_L1 )
273 res.setGroup( componentMap.value( u"long_name"_s ).toString() );
274 }
275 }
276 }
277
278 if ( geometry.contains( u"viewport"_s ) )
279 {
280 const QVariantMap viewport = geometry.value( u"viewport"_s ).toMap();
281 const QVariantMap northEast = viewport.value( u"northeast"_s ).toMap();
282 const QVariantMap southWest = viewport.value( u"southwest"_s ).toMap();
283 res.setViewport( QgsRectangle( southWest.value( u"lng"_s ).toDouble(),
284 southWest.value( u"lat"_s ).toDouble(),
285 northEast.value( u"lng"_s ).toDouble(),
286 northEast.value( u"lat"_s ).toDouble()
287 ) );
288 }
289
290 res.setAdditionalAttributes( attributes );
291 return res;
292}
293
294void QgsGoogleMapsGeocoder::setEndpoint( const QString &endpoint )
295{
296 mEndpoint = endpoint;
297}
298
300{
301 return mApiKey;
302}
303
305{
306 mApiKey = apiKey;
307}
308
310{
311 return mRegion;
312}
313
315{
316 mRegion = region;
317}
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:280
@ Point
Point.
Definition qgis.h:282
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:76
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:44
QFlags< Flag > Flags
Definition qgsgeocoder.h:47
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)