27#include <QJsonDocument>
29#include <QNetworkRequest>
34using namespace Qt::StringLiterals;
36QMutex QgsNominatimGeocoder::sMutex;
39qint64 QgsNominatimGeocoder::sLastRequestTimestamp = 0;
44 , mEndpoint( u
"https://nominatim.qgis.org/search"_s )
58 fields.
append(
QgsField( u
"osm_type"_s, QMetaType::Type::QString ) );
59 fields.
append(
QgsField( u
"display_name"_s, QMetaType::Type::QString ) );
60 fields.
append(
QgsField( u
"place_id"_s, QMetaType::Type::QString ) );
64 fields.
append(
QgsField( u
"village"_s, QMetaType::Type::QString ) );
65 fields.
append(
QgsField( u
"city_district"_s, QMetaType::Type::QString ) );
69 fields.
append(
QgsField( u
"country"_s, QMetaType::Type::QString ) );
70 fields.
append(
QgsField( u
"postcode"_s, QMetaType::Type::QString ) );
93 QgsDebugError(
"Could not transform geocode bounds to WGS84" );
99 const QMutexLocker locker( &sMutex );
100 const auto it = sCachedResultsNominatim()->constFind( url );
101 if ( it != sCachedResultsNominatim()->constEnd() )
106 while ( QDateTime::currentMSecsSinceEpoch() - sLastRequestTimestamp < 1000 / mRequestsPerSecond )
108 QThread::msleep( 50 );
110 return QList<QgsGeocoderResult>();
113 QNetworkRequest request( url );
119 sLastRequestTimestamp = QDateTime::currentMSecsSinceEpoch();
128 const QJsonDocument doc = QJsonDocument::fromJson( newReq.
reply().
content(), &err );
134 const QVariantList results = doc.array().toVariantList();
135 if ( results.isEmpty() )
137 sCachedResultsNominatim()->insert( url, QList<QgsGeocoderResult>() );
138 return QList<QgsGeocoderResult>();
141 QList< QgsGeocoderResult > matches;
142 matches.reserve( results.size() );
143 for (
const QVariant &result : results )
148 sCachedResultsNominatim()->insert( url, matches );
155 QUrl res( mEndpoint );
157 query.addQueryItem( u
"format"_s, u
"json"_s );
158 query.addQueryItem( u
"addressdetails"_s, u
"1"_s );
161 query.addQueryItem( u
"viewbox"_s, bounds.
toString( 7 ).replace(
" : "_L1,
","_L1 ) );
163 if ( !mCountryCodes.isEmpty() )
165 query.addQueryItem( u
"countrycodes"_s, mCountryCodes.toLower() );
167 query.addQueryItem( u
"q"_s, address );
168 res.setQuery( query );
175 const double latitude = json.value( u
"lat"_s ).toDouble();
176 const double longitude = json.value( u
"lon"_s ).toDouble();
184 QVariantMap attributes;
186 if ( json.contains( u
"display_name"_s ) )
187 attributes.insert( u
"display_name"_s, json.value( u
"display_name"_s ).toString() );
188 if ( json.contains( u
"place_id"_s ) )
189 attributes.insert( u
"place_id"_s, json.value( u
"place_id"_s ).toString() );
190 if ( json.contains( u
"osm_type"_s ) )
191 attributes.insert( u
"osm_type"_s, json.value( u
"osm_type"_s ).toString() );
192 if ( json.contains( u
"class"_s ) )
193 attributes.insert( u
"class"_s, json.value( u
"class"_s ).toString() );
194 if ( json.contains( u
"type"_s ) )
195 attributes.insert( u
"type"_s, json.value( u
"type"_s ).toString() );
197 if ( json.contains( u
"address"_s ) )
199 const QVariantMap address_components = json.value( u
"address"_s ).toMap();
200 if ( address_components.contains( u
"road"_s ) )
201 attributes.insert( u
"road"_s, address_components.value( u
"road"_s ).toString() );
202 if ( address_components.contains( u
"village"_s ) )
203 attributes.insert( u
"village"_s, address_components.value( u
"village"_s ).toString() );
204 if ( address_components.contains( u
"city_district"_s ) )
205 attributes.insert( u
"city_district"_s, address_components.value( u
"city_district"_s ).toString() );
206 if ( address_components.contains( u
"town"_s ) )
207 attributes.insert( u
"town"_s, address_components.value( u
"town"_s ).toString() );
208 if ( address_components.contains( u
"city"_s ) )
209 attributes.insert( u
"city"_s, address_components.value( u
"city"_s ).toString() );
210 if ( address_components.contains( u
"state"_s ) )
212 attributes.insert( u
"state"_s, address_components.value( u
"state"_s ).toString() );
213 res.
setGroup( address_components.value( u
"state"_s ).toString() );
215 if ( address_components.contains( u
"country"_s ) )
216 attributes.insert( u
"country"_s, address_components.value( u
"country"_s ).toString() );
217 if ( address_components.contains( u
"postcode"_s ) )
218 attributes.insert( u
"postcode"_s, address_components.value( u
"postcode"_s ).toString() );
221 if ( json.contains( u
"boundingbox"_s ) )
223 const QVariantList boundingBox = json.value( u
"boundingbox"_s ).toList();
224 if ( boundingBox.size() == 4 )
226 boundingBox.at( 0 ).toDouble(),
227 boundingBox.at( 3 ).toDouble(),
228 boundingBox.at( 1 ).toDouble() ) );
247 return mCountryCodes;
WkbType
The WKB type describes the number of dimensions a geometry has.
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).
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.
bool isCanceled() const
Tells whether the operation has been canceled already.
Encapsulate a field in an attribute table or data source.
Container of fields for a vector layer.
bool append(const QgsField &field, Qgis::FieldOrigin origin=Qgis::FieldOrigin::Provider, int originIndex=-1)
Appends a field.
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...
@ GeocodesStrings
Can geocode string input values.
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.
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)
#define QgsSetRequestInitiatorClass(request, _class)