Skip to content

Commit

Permalink
Cache google maps geocoder results so that we don't send the same
Browse files Browse the repository at this point in the history
request multiple times
  • Loading branch information
nyalldawson committed Dec 15, 2020
1 parent 222c3c5 commit 3a3e771
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
Expand Up @@ -8,6 +8,7 @@




class QgsGoogleMapsGeocoder : QgsGeocoderInterface
{
%Docstring
Expand Down
18 changes: 18 additions & 0 deletions src/core/geocoding/qgsgooglemapsgeocoder.cpp
Expand Up @@ -18,12 +18,17 @@
#include "qgslogger.h"
#include "qgsnetworkaccessmanager.h"
#include "qgsblockingnetworkrequest.h"
#include "qgsreadwritelocker.h"
#include <QUrl>
#include <QUrlQuery>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonObject>

QReadWriteLock QgsGoogleMapsGeocoder::sMutex;
QMap< QUrl, QList< QgsGeocoderResult > > QgsGoogleMapsGeocoder::sCachedResults;


QgsGoogleMapsGeocoder::QgsGoogleMapsGeocoder( const QString &apiKey, const QString &regionBias )
: QgsGeocoderInterface()
, mApiKey( apiKey )
Expand Down Expand Up @@ -81,6 +86,14 @@ QList<QgsGeocoderResult> QgsGoogleMapsGeocoder::geocodeString( const QString &st

const QUrl url = requestUrl( string, bounds );

QgsReadWriteLocker locker( sMutex, QgsReadWriteLocker::Read );
auto it = sCachedResults.constFind( url );
if ( it != sCachedResults.constEnd() )
{
return *it;
}
locker.unlock();

QNetworkRequest request( url );
QgsSetRequestInitiatorClass( request, QStringLiteral( "QgsGoogleMapsGeocoder" ) );

Expand Down Expand Up @@ -120,9 +133,12 @@ QList<QgsGeocoderResult> QgsGoogleMapsGeocoder::geocodeString( const QString &st
}

// all good!
locker.changeMode( QgsReadWriteLocker::Write );

const QVariantList results = res.value( QStringLiteral( "results" ) ).toList();
if ( results.empty() )
{
sCachedResults.insert( url, QList<QgsGeocoderResult>() );
return QList<QgsGeocoderResult>();
}

Expand All @@ -132,6 +148,8 @@ QList<QgsGeocoderResult> QgsGoogleMapsGeocoder::geocodeString( const QString &st
{
matches << jsonToResult( result.toMap() );
}
sCachedResults.insert( url, matches );

return matches;
}

Expand Down
5 changes: 5 additions & 0 deletions src/core/geocoding/qgsgooglemapsgeocoder.h
Expand Up @@ -19,6 +19,8 @@
#include "qgis_core.h"
#include "qgsgeocoder.h"

#include <QMutex>

/**
* \ingroup core
* A geocoder which uses the Google Map geocoding API to retrieve results.
Expand Down Expand Up @@ -111,6 +113,9 @@ class CORE_EXPORT QgsGoogleMapsGeocoder : public QgsGeocoderInterface
QString mRegion;
QString mEndpoint;

static QReadWriteLock sMutex;
static QMap< QUrl, QList< QgsGeocoderResult > > sCachedResults;

};

#endif // QGSGOOGLEMAPSGEOCODER_H

0 comments on commit 3a3e771

Please sign in to comment.