Offline geocode

View on GitHubSample viewer app

Geocode addresses to locations and reverse geocode locations to addresses offline.

screenshot

Use case

You can use an address locator file to geocode addresses and locations. For example, you could provide offline geocoding capabilities to field workers repairing critical infrastructure in a disaster when network availability is limited.

How to use the sample

Type the address in the Search menu option or select from the list to Geocode the address and view the result on the map. Tap the location you want to reverse geocode. Select the pin to highlight the PictureMarkerSymbol (i.e. single tap on the pin) and then tap-hold and drag on the map to get real-time geocoding.

How it works

  1. Use the path of a .loc file to create a LocatorTask object.
  2. Set up GeocodeParameters and call geocode to get geocode results.

Relevant API

  • GeocodeParameters
  • GeocodeResult
  • LocatorTask
  • ReverseGeocodeParameters

Offline Data

Read more about how to set up the sample's offline data here.

Link Local Location
SanDiego tpkx File <userhome>/ArcGIS/Runtime/Data/tpkx/streetmap_SD.tpkx
SanDiego loc Files <userhome>/ArcGIS/Runtime/Data/Locators/SanDiegoStreetAddressLocator/SanDiego_StreetAddress.loc

Tags

geocode, geocoder, locator, offline, package, query, search

Sample Code

OfflineGeocode.cppOfflineGeocode.cppOfflineGeocode.hOfflineGeocode.qml
Use dark colors for code blocksCopy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// [WriteFile Name=OfflineGeocode, Category=Search]
// [Legal]
// Copyright 2016 Esri.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// [Legal]

#ifdef PCH_BUILD
#include "pch.hpp"
#endif // PCH_BUILD

#include "OfflineGeocode.h"

#include "Map.h"
#include "Point.h"
#include "Graphic.h"
#include "CalloutData.h"
#include "LocatorTask.h"
#include "MapQuickView.h"
#include "GeocodeResult.h"
#include "GraphicsOverlay.h"
#include "SuggestListModel.h"
#include "ArcGISTiledLayer.h"
#include "GeocodeParameters.h"
#include "PictureMarkerSymbol.h"
#include "IdentifyGraphicsOverlayResult.h"
#include "MapViewTypes.h"
#include "Error.h"
#include "GraphicsOverlayListModel.h"
#include "GraphicListModel.h"
#include "LayerListModel.h"
#include "TileCache.h"
#include "Basemap.h"
#include "SpatialReference.h"
#include "Viewpoint.h"
#include "ErrorException.h"

#include <QFuture>
#include <QScopedPointer>
#include <QtCore/qglobal.h>
#include <memory>
#include <QUuid>
#include <QStandardPaths>

using namespace Esri::ArcGISRuntime;

// helper method to get cross platform data path
namespace
{
  QString defaultDataPath()
  {
    QString dataPath;

  #ifdef Q_OS_IOS
    dataPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
  #else
    dataPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
  #endif

    return dataPath;
  }
} // namespace

using namespace Esri::ArcGISRuntime;

OfflineGeocode::OfflineGeocode(QQuickItem* parent):
  QQuickItem(parent),
  m_dataPath(defaultDataPath() + "/ArcGIS/Runtime/Data/")
{
}

OfflineGeocode::~OfflineGeocode() = default;

void OfflineGeocode::init()
{
  qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView");
  qmlRegisterType<OfflineGeocode>("Esri.Samples", 1, 0, "OfflineGeocodeSample");
  qmlRegisterUncreatableType<CalloutData>("Esri.Samples", 1, 0, "CalloutData", "CalloutData is an uncreatable type");
  qmlRegisterUncreatableType<SuggestListModel>("Esri.Samples", 1, 0, "SuggestListModel", "SuggestionListModel is an uncreatable type");
}

void OfflineGeocode::componentComplete()
{
  QQuickItem::componentComplete();

  // find QML MapView component
  m_mapView = findChild<MapQuickView*>("mapView");
  m_mapView->setWrapAroundMode(WrapAroundMode::Disabled);

  // create a tiled layer using a local .tpkx file
  TileCache* tileCache = new TileCache(m_dataPath + "tpkx/streetmap_SD.tpkx", this);
  connect(tileCache, &TileCache::errorOccurred, this, &OfflineGeocode::logError);

  m_tiledLayer = new ArcGISTiledLayer(tileCache, this);

  // create basemap and add tiled layer
  Basemap* basemap = new Basemap(this);
  basemap->baseLayers()->append(m_tiledLayer);

  // create map using basemap
  m_map = new Map(basemap, this);
  m_map->setInitialViewpoint(Viewpoint(Point(-13042254.715252, 3857970.236806, SpatialReference(3857)), 2e4));

  // Set map to map view
  m_mapView->setMap(m_map);

  // create locator task
  //! [OfflineGeocode create LocatorTask]
  m_locatorTask = new LocatorTask(m_dataPath + "Locators/SanDiegoStreetAddressLocator/SanDiego_StreetAddress.loc", this);
  //! [OfflineGeocode create LocatorTask]

  // set the suggestions Q_PROPERTY
  m_suggestListModel = m_locatorTask->suggestions();
  emit suggestionsChanged();

  // set geocode parameters
  m_geocodeParameters.setMinScore(75);
  m_geocodeParameters.setMaxResults(1);
  m_reverseGeocodeParameters.setMaxResults(1);

  // create graphics overlay and add pin graphic
  m_graphicsOverlay = new GraphicsOverlay(this);
  PictureMarkerSymbol* pinSymbol = new PictureMarkerSymbol(QUrl("qrc:/Samples/Search/OfflineGeocode/red_pin.png"), this);
  pinSymbol->setHeight(36);
  pinSymbol->setWidth(19);
  pinSymbol->setOffsetY(pinSymbol->height() / 2);
  m_pinGraphic = new Graphic(Point(-13042254.715252, 3857970.236806, SpatialReference(3857)), pinSymbol, this);
  m_pinGraphic->setVisible(false);
  m_graphicsOverlay->graphics()->append(m_pinGraphic);
  m_mapView->graphicsOverlays()->append(m_graphicsOverlay);

  // initialize callout
  m_mapView->calloutData()->setVisible(false);
  m_mapView->calloutData()->setTitle("Address");
  m_calloutData = m_mapView->calloutData();

  connectSignals();
}

void OfflineGeocode::geocodeWithText(const QString& address)
{
  m_locatorTask->geocodeWithParametersAsync(address, m_geocodeParameters).then(this, [this](const QList<GeocodeResult>& geocodeResults)
  {
    onGeocodingCompleted_(geocodeResults);
  }).onFailed(this, [this](const ErrorException& e)
  {
    logException(e);
  });
}

void OfflineGeocode::geocodeWithSuggestion(int index)
{
  m_locatorTask->geocodeWithSuggestResultAndParametersAsync(m_suggestListModel->suggestResults().at(index), m_geocodeParameters)
      .then(this, [this](const QList<GeocodeResult>& geocodeResults)
  {
    onGeocodingCompleted_(geocodeResults);
  }).onFailed(this, [this](const ErrorException& e)
  {
    logException(e);
  });
}

void OfflineGeocode::setSuggestionsText(const QString& searchText)
{
  m_suggestListModel->setSearchText(searchText);
}

void OfflineGeocode::logError(const Error& error)
{
  setErrorMessage( QString("%1: %2").arg(error.message(), error.additionalMessage()));
}

void OfflineGeocode::logException(const ErrorException& exception)
{
  logError(exception.error());
}

SuggestListModel* OfflineGeocode::suggestions() const
{
  return m_suggestListModel;
}

bool OfflineGeocode::geocodeInProgress() const
{
  return m_geocodeInProgress;
}

bool OfflineGeocode::noResults() const
{
  return m_noResults;
}

bool OfflineGeocode::suggestInProgress() const
{
  return m_suggestInProgress;
}

void OfflineGeocode::connectSignals()
{
  connect(m_map, &Map::errorOccurred, this, &OfflineGeocode::logError);
  connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent)
  {
    m_clickedPoint = m_mapView->screenToLocation(mouseEvent.position().x(), mouseEvent.position().y());
    m_mapView->identifyGraphicsOverlayAsync(m_graphicsOverlay, mouseEvent.position(), 5, false, 1)
        .then(this, [this](IdentifyGraphicsOverlayResult* rawIdentifyResult)
    {
      // Delete rawIdentifyResult when we leave scope.
      auto identifyResult = std::unique_ptr<IdentifyGraphicsOverlayResult>(rawIdentifyResult);

      if (!identifyResult)
        return;

      // if user clicked on pin, display callout
      const QList<Graphic*> graphics = identifyResult->graphics();
      if (graphics.count() > 0)
        m_calloutData->setVisible(true);

      // otherwise, reverse geocode at that point
      else
      {
        m_isReverseGeocode = true;
        m_locatorTask->reverseGeocodeWithParametersAsync(m_clickedPoint, m_reverseGeocodeParameters)
            .then(this, [this](const QList<GeocodeResult>& geocodeResults)
        {
          onGeocodingCompleted_(geocodeResults);
        }).onFailed(this, [this](const ErrorException& e)
        {
          logException(e);
        });

        m_geocodeInProgress = true;
        emit geocodeInProgressChanged();
      }
    }).onFailed(this, [this](const ErrorException& e)
    {
      logException(e);
    });
  });

  connect(m_mapView, &MapQuickView::mousePressedAndHeld, this, [this](QMouseEvent& mouseEvent)
  {
    m_isPressAndHold = true;
    m_isReverseGeocode = true;

    // reverse geocode
    m_locatorTask->reverseGeocodeWithParametersAsync(Point(m_mapView->screenToLocation(mouseEvent.position().x(), mouseEvent.position().y())), m_reverseGeocodeParameters)
        .then(this, [this](const QList<GeocodeResult>& geocodeResults)
    {
      onGeocodingCompleted_(geocodeResults);
    }).onFailed(this, [this](const ErrorException& e)
    {
      logException(e);
    });

    // make busy indicator visible
    m_geocodeInProgress = true;
    emit geocodeInProgressChanged();
  });

  connect(m_mapView, &MapQuickView::mouseMoved, this, [this](QMouseEvent& mouseEvent)
  {
    // if user is dragging mouse hold, realtime reverse geocode
    if (m_isPressAndHold)
    {
      m_locatorTask->reverseGeocodeWithParametersAsync(Point(m_mapView->screenToLocation(mouseEvent.position().x(), mouseEvent.position().y())), m_reverseGeocodeParameters)
          .then(this, [this](const QList<GeocodeResult>& geocodeResults)
      {
        onGeocodingCompleted_(geocodeResults);
      }).onFailed(this, [this](const ErrorException& e)
      {
        logException(e);
      });

      m_geocodeInProgress = true;
      emit geocodeInProgressChanged();
    }
  });

  // reset after user stops holding down mouse
  connect(m_mapView, &MapQuickView::mouseReleased, this, [this]()
  {
    m_isPressAndHold = false;
    m_isReverseGeocode = false;
  });

  // dismiss no results notification and suggestions on mouse press
  connect(m_mapView, &MapQuickView::mousePressed, this, [this]()
  {
    m_noResults = false;
    emit noResultsChanged();
    emit dismissSuggestions();
  });

  connect(m_suggestListModel, &SuggestListModel::errorOccurred, this, &OfflineGeocode::logError);
  connect(m_suggestListModel, &SuggestListModel::suggestInProgressChanged, this, [this]()
  {
    m_suggestInProgress = m_suggestListModel->suggestInProgress();
    emit suggestInProgressChanged();
  });
}

void OfflineGeocode::onGeocodingCompleted_(const QList<GeocodeResult>& geocodeResults)
{
  // dismiss busy indicator
  m_geocodeInProgress = false;
  emit geocodeInProgressChanged();

  // dismiss callouts
  m_calloutData->setVisible(false);
  m_pinGraphic->setVisible(false);

  // if there are no matching results, notify user and stop processing
  if (geocodeResults.isEmpty())
  {
    m_noResults = true;
    emit noResultsChanged();
    return;
  }

  // dismiss no results notification
  m_noResults = false;
  emit noResultsChanged();

  // zoom to result's extent
  m_mapView->setViewpointCenterAsync(geocodeResults.at(0).displayLocation());

  // set pin graphic's location
  m_pinGraphic->setGeometry(geocodeResults.at(0).displayLocation());
  m_pinGraphic->setVisible(true);

  // set callout location and detail
  m_calloutData->setDetail(geocodeResults.at(0).label());
  m_calloutData->setGeoElement(m_pinGraphic);

  if (m_isReverseGeocode)
    m_calloutData->setVisible(true);

  // continue reverse geocoding if user is pressing and holding
  if (!m_isPressAndHold)
    m_isReverseGeocode = false;
}

QString OfflineGeocode::errorMessage() const
{
  return m_errorMsg;
}

void OfflineGeocode::setErrorMessage(const QString& msg)
{
  m_errorMsg = msg;
  qDebug() << m_errorMsg;
  emit errorMessageChanged();
}

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.