QGIS API Documentation 3.99.0-Master (2fe06baccd8)
Loading...
Searching...
No Matches
qgsnominatimgeocoder.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsnominatimgeocoder.cpp
3 ---------------
4 Date : December 2020
5 Copyright : (C) 2020 by Mathieu Pellerin
6 Email : nirvn dot asia 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"
24
25#include <QDateTime>
26#include <QJsonArray>
27#include <QJsonDocument>
28#include <QMutex>
29#include <QNetworkRequest>
30#include <QUrl>
31#include <QUrlQuery>
32
33QMutex QgsNominatimGeocoder::sMutex;
34typedef QMap< QUrl, QList< QgsGeocoderResult > > CachedGeocodeResult;
35Q_GLOBAL_STATIC( CachedGeocodeResult, sCachedResultsNominatim )
36qint64 QgsNominatimGeocoder::sLastRequestTimestamp = 0;
37
40 , mCountryCodes( countryCodes )
41 , mEndpoint( QStringLiteral( "https://nominatim.qgis.org/search" ) )
42{
43 if ( !endpoint.isEmpty() )
44 mEndpoint = endpoint;
45}
46
51
53{
54 QgsFields fields;
55 fields.append( QgsField( QStringLiteral( "osm_type" ), QMetaType::Type::QString ) );
56 fields.append( QgsField( QStringLiteral( "display_name" ), QMetaType::Type::QString ) );
57 fields.append( QgsField( QStringLiteral( "place_id" ), QMetaType::Type::QString ) );
58 fields.append( QgsField( QStringLiteral( "class" ), QMetaType::Type::QString ) );
59 fields.append( QgsField( QStringLiteral( "type" ), QMetaType::Type::QString ) );
60 fields.append( QgsField( QStringLiteral( "road" ), QMetaType::Type::QString ) );
61 fields.append( QgsField( QStringLiteral( "village" ), QMetaType::Type::QString ) );
62 fields.append( QgsField( QStringLiteral( "city_district" ), QMetaType::Type::QString ) );
63 fields.append( QgsField( QStringLiteral( "town" ), QMetaType::Type::QString ) );
64 fields.append( QgsField( QStringLiteral( "city" ), QMetaType::Type::QString ) );
65 fields.append( QgsField( QStringLiteral( "state" ), QMetaType::Type::QString ) );
66 fields.append( QgsField( QStringLiteral( "country" ), QMetaType::Type::QString ) );
67 fields.append( QgsField( QStringLiteral( "postcode" ), QMetaType::Type::QString ) );
68 return fields;
69}
70
75
76QList<QgsGeocoderResult> QgsNominatimGeocoder::geocodeString( const QString &string, const QgsGeocoderContext &context, QgsFeedback *feedback ) const
77{
78 QgsRectangle bounds;
79 if ( !context.areaOfInterest().isEmpty() )
80 {
81 QgsGeometry g = context.areaOfInterest();
82 const QgsCoordinateTransform ct( context.areaOfInterestCrs(), QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ), context.transformContext() );
83 try
84 {
85 g.transform( ct );
86 bounds = g.boundingBox();
87 }
88 catch ( QgsCsException & )
89 {
90 QgsDebugError( "Could not transform geocode bounds to WGS84" );
91 }
92 }
93
94 const QUrl url = requestUrl( string, bounds );
95
96 const QMutexLocker locker( &sMutex );
97 const auto it = sCachedResultsNominatim()->constFind( url );
98 if ( it != sCachedResultsNominatim()->constEnd() )
99 {
100 return *it;
101 }
102
103 while ( QDateTime::currentMSecsSinceEpoch() - sLastRequestTimestamp < 1000 / mRequestsPerSecond )
104 {
105 QThread::msleep( 50 );
106 if ( feedback && feedback->isCanceled() )
107 return QList<QgsGeocoderResult>();
108 }
109
110 QNetworkRequest request( url );
111 QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsNominatimGeocoder" ) );
112
114 const QgsBlockingNetworkRequest::ErrorCode errorCode = newReq.get( request, false, feedback );
115
116 sLastRequestTimestamp = QDateTime::currentMSecsSinceEpoch();
117
118 if ( errorCode != QgsBlockingNetworkRequest::NoError )
119 {
120 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( newReq.errorMessage() );
121 }
122
123 // Parse data
124 QJsonParseError err;
125 const QJsonDocument doc = QJsonDocument::fromJson( newReq.reply().content(), &err );
126 if ( doc.isNull() )
127 {
128 return QList<QgsGeocoderResult>() << QgsGeocoderResult::errorResult( err.errorString() );
129 }
130
131 const QVariantList results = doc.array().toVariantList();
132 if ( results.isEmpty() )
133 {
134 sCachedResultsNominatim()->insert( url, QList<QgsGeocoderResult>() );
135 return QList<QgsGeocoderResult>();
136 }
137
138 QList< QgsGeocoderResult > matches;
139 matches.reserve( results.size() );
140 for ( const QVariant &result : results )
141 {
142 matches << jsonToResult( result.toMap() );
143 }
144
145 sCachedResultsNominatim()->insert( url, matches );
146
147 return matches;
148}
149
150QUrl QgsNominatimGeocoder::requestUrl( const QString &address, const QgsRectangle &bounds ) const
151{
152 QUrl res( mEndpoint );
153 QUrlQuery query;
154 query.addQueryItem( QStringLiteral( "format" ), QStringLiteral( "json" ) );
155 query.addQueryItem( QStringLiteral( "addressdetails" ), QStringLiteral( "1" ) );
156 if ( !bounds.isNull() && bounds.isFinite() )
157 {
158 query.addQueryItem( QStringLiteral( "viewbox" ), bounds.toString( 7 ).replace( QLatin1String( " : " ), QLatin1String( "," ) ) );
159 }
160 if ( !mCountryCodes.isEmpty() )
161 {
162 query.addQueryItem( QStringLiteral( "countrycodes" ), mCountryCodes.toLower() );
163 }
164 query.addQueryItem( QStringLiteral( "q" ), address );
165 res.setQuery( query );
166
167 return res;
168}
169
171{
172 const double latitude = json.value( QStringLiteral( "lat" ) ).toDouble();
173 const double longitude = json.value( QStringLiteral( "lon" ) ).toDouble();
174
175 const QgsGeometry geom = QgsGeometry::fromPointXY( QgsPointXY( longitude, latitude ) );
176
177 QgsGeocoderResult res( json.value( QStringLiteral( "display_name" ) ).toString(),
178 geom,
179 QgsCoordinateReferenceSystem( QStringLiteral( "EPSG:4326" ) ) );
180
181 QVariantMap attributes;
182
183 if ( json.contains( QStringLiteral( "display_name" ) ) )
184 attributes.insert( QStringLiteral( "display_name" ), json.value( QStringLiteral( "display_name" ) ).toString() );
185 if ( json.contains( QStringLiteral( "place_id" ) ) )
186 attributes.insert( QStringLiteral( "place_id" ), json.value( QStringLiteral( "place_id" ) ).toString() );
187 if ( json.contains( QStringLiteral( "osm_type" ) ) )
188 attributes.insert( QStringLiteral( "osm_type" ), json.value( QStringLiteral( "osm_type" ) ).toString() );
189 if ( json.contains( QStringLiteral( "class" ) ) )
190 attributes.insert( QStringLiteral( "class" ), json.value( QStringLiteral( "class" ) ).toString() );
191 if ( json.contains( QStringLiteral( "type" ) ) )
192 attributes.insert( QStringLiteral( "type" ), json.value( QStringLiteral( "type" ) ).toString() );
193
194 if ( json.contains( QStringLiteral( "address" ) ) )
195 {
196 const QVariantMap address_components = json.value( QStringLiteral( "address" ) ).toMap();
197 if ( address_components.contains( QStringLiteral( "road" ) ) )
198 attributes.insert( QStringLiteral( "road" ), address_components.value( QStringLiteral( "road" ) ).toString() );
199 if ( address_components.contains( QStringLiteral( "village" ) ) )
200 attributes.insert( QStringLiteral( "village" ), address_components.value( QStringLiteral( "village" ) ).toString() );
201 if ( address_components.contains( QStringLiteral( "city_district" ) ) )
202 attributes.insert( QStringLiteral( "city_district" ), address_components.value( QStringLiteral( "city_district" ) ).toString() );
203 if ( address_components.contains( QStringLiteral( "town" ) ) )
204 attributes.insert( QStringLiteral( "town" ), address_components.value( QStringLiteral( "town" ) ).toString() );
205 if ( address_components.contains( QStringLiteral( "city" ) ) )
206 attributes.insert( QStringLiteral( "city" ), address_components.value( QStringLiteral( "city" ) ).toString() );
207 if ( address_components.contains( QStringLiteral( "state" ) ) )
208 {
209 attributes.insert( QStringLiteral( "state" ), address_components.value( QStringLiteral( "state" ) ).toString() );
210 res.setGroup( address_components.value( QStringLiteral( "state" ) ).toString() );
211 }
212 if ( address_components.contains( QStringLiteral( "country" ) ) )
213 attributes.insert( QStringLiteral( "country" ), address_components.value( QStringLiteral( "country" ) ).toString() );
214 if ( address_components.contains( QStringLiteral( "postcode" ) ) )
215 attributes.insert( QStringLiteral( "postcode" ), address_components.value( QStringLiteral( "postcode" ) ).toString() );
216 }
217
218 if ( json.contains( QStringLiteral( "boundingbox" ) ) )
219 {
220 const QVariantList boundingBox = json.value( QStringLiteral( "boundingbox" ) ).toList();
221 if ( boundingBox.size() == 4 )
222 res.setViewport( QgsRectangle( boundingBox.at( 2 ).toDouble(),
223 boundingBox.at( 0 ).toDouble(),
224 boundingBox.at( 3 ).toDouble(),
225 boundingBox.at( 1 ).toDouble() ) );
226 }
227
228 res.setAdditionalAttributes( attributes );
229 return res;
230}
231
233{
234 return mEndpoint;
235}
236
238{
239 mEndpoint = endpoint;
240}
241
243{
244 return mCountryCodes;
245}
246
248{
249 mCountryCodes = countryCodes;
250}
WkbType
The WKB type describes the number of dimensions a geometry has.
Definition qgis.h:277
@ Point
Point.
Definition qgis.h:279
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
bool isCanceled() const
Tells whether the operation has been canceled already.
Definition qgsfeedback.h:53
Encapsulate a field in an attribute table or data source.
Definition qgsfield.h:54
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:73
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.
QByteArray content() const
Returns the reply content.
QList< QgsGeocoderResult > geocodeString(const QString &string, const QgsGeocoderContext &context, QgsFeedback *feedback=nullptr) const override
Geocodes a string.
QgsGeocoderResult jsonToResult(const QVariantMap &json) const
Converts a JSON result returned from the Nominatim service to a geocoder result object.
QgsNominatimGeocoder(const QString &countryCodes=QString(), const QString &endpoint=QString())
Constructor for QgsNominatimGeocoder.
QString countryCodes() const
Returns the optional region bias which will be used to prioritize results in a certain region.
QString endpoint() const
Returns the API endpoint used for requests.
QgsFields appendedFields() const override
Returns a set of newly created fields which will be appended to existing features during the geocode ...
Qgis::WkbType wkbType() const override
Returns the WKB type of geometries returned by the geocoder.
void setEndpoint(const QString &endpoint)
Sets a specific API endpoint to use for requests.
Flags flags() const override
Returns the geocoder's capability flags.
void setCountryCodes(const QString &countryCodes)
Sets 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.
Represents a 2D point.
Definition qgspointxy.h:60
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...
bool isFinite() const
Returns true if the rectangle has finite boundaries.
Q_GLOBAL_STATIC(QReadWriteLock, sDefinitionCacheLock)
QMap< QUrl, QList< QgsGeocoderResult > > CachedGeocodeResult
#define QgsDebugError(str)
Definition qgslogger.h:57
#define QgsSetRequestInitiatorClass(request, _class)