Find the location for an address.

Use case
A user can input a raw address into your app’s search bar and zoom to the address location.
How to use the sample
For simplicity, the sample comes loaded with a set of suggested addresses. Choose an address from the suggestions or submit your own address to show its location on the map in a callout.
How it works
- Create a
LocatorTaskusing the URL to a locator service. - Set the
GeocodeParametersfor the locator task and specify the geocode’s attributes. - Get the matching results from the
GeocodeResultusinglocatorTask::geocodeWithParametersAsync(addressString, geocodeParameters). - Create a
Graphicwith the geocode result’s location and store the geocode result’s attributes in the graphic’s attributes. - Show the graphic in a
GraphicsOverlay.
Relevant API
- GeocodeParameters
- GeocodeResult
- LocatorTask
About the data
This sample uses the World Geocoding Service.
Tags
address, geocode, locator, search
Sample Code
// [WriteFile Name=FindAddress, 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
// sample headers#include "FindAddress.h"
// ArcGIS Maps SDK headers#include "AttributeListModel.h"#include "Basemap.h"#include "CalloutData.h"#include "Envelope.h"#include "GeocodeParameters.h"#include "GeocodeResult.h"#include "Graphic.h"#include "GraphicListModel.h"#include "GraphicsOverlay.h"#include "GraphicsOverlayListModel.h"#include "IdentifyGraphicsOverlayResult.h"#include "LocatorTask.h"#include "Map.h"#include "MapQuickView.h"#include "MapTypes.h"#include "PictureMarkerSymbol.h"#include "Point.h"#include "SimpleRenderer.h"
// Qt headers#include <QFuture>#include <QUrl>#include <QUuid>
// STL headers#include <memory>
using namespace Esri::ArcGISRuntime;
FindAddress::FindAddress(QQuickItem* parent) : QQuickItem(parent){}
FindAddress::~FindAddress() = default;
void FindAddress::init(){ qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<FindAddress>("Esri.Samples", 1, 0, "FindAddressSample"); qmlRegisterUncreatableType<CalloutData>("Esri.Samples", 1, 0, "CalloutData", "CalloutData is an uncreatable type");}
void FindAddress::componentComplete(){ QQuickItem::componentComplete();
// find QML MapView component m_mapView = findChild<MapQuickView*>("mapView");
// create a new basemap instance Basemap* basemap = new Basemap(BasemapStyle::ArcGISImagery, this); // create a new map instance m_map = new Map(basemap, this); // set map on the map view m_mapView->setMap(m_map); // create graphics overlay and add to map view m_graphicsOverlay = new GraphicsOverlay(this); m_mapView->graphicsOverlays()->append(m_graphicsOverlay);
// set a renderer on the graphics overlay SimpleRenderer* simpleRenderer = new SimpleRenderer(this); PictureMarkerSymbol* pictureMarkerSymbol = new PictureMarkerSymbol(QUrl("qrc:/Samples/Search/FindAddress/pin_circle_red.png"), this); pictureMarkerSymbol->setWidth(35); pictureMarkerSymbol->setHeight(35); pictureMarkerSymbol->setOffsetY(pictureMarkerSymbol->height() / 2); simpleRenderer->setSymbol(pictureMarkerSymbol); m_graphicsOverlay->setRenderer(simpleRenderer); m_graphic = new Graphic(this); m_graphicsOverlay->graphics()->append(m_graphic);
// create locator task and parameters //! [FindAddress create LocatorTask] m_locatorTask = new LocatorTask(QUrl("https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer"), this); //! [FindAddress create LocatorTask] m_geocodeParameters.setMinScore(75); m_geocodeParameters.setResultAttributeNames(QStringList { "Place_addr", "Match_addr" });
connectSignals();}
void FindAddress::connectSignals(){ //! [FindAddress geocodeCompleted handler]
// connect to the mouse click signal on the MapQuickView connect(m_mapView, &MapQuickView::mouseClicked, this, [this](QMouseEvent& mouseEvent) { // set the properties for qml m_mapView->calloutData()->setLocation(m_mapView->screenToLocation(mouseEvent.position().x(), mouseEvent.position().y())); emit hideCallout();
// call identify on the map view m_mapView->identifyGraphicsOverlayAsync(m_graphicsOverlay, mouseEvent.position(), 5, false, 1).then(this, [this](IdentifyGraphicsOverlayResult* rawIdentifyResult) { // Delete rawIdentifyResult on leaving scope. auto identifyResult = std::unique_ptr<IdentifyGraphicsOverlayResult>(rawIdentifyResult);
if (!identifyResult) return;
const QList<Graphic*> graphics = identifyResult->graphics(); if (graphics.isEmpty()) return;
const AttributeListModel* attributes = graphics.at(0)->attributes(); const QString calloutText = attributes->attributeValue("Match_addr").toString(); m_mapView->calloutData()->setTitle(calloutText); emit showCallout(); }); });}
void FindAddress::geocodeAddress(const QString& address){ //! [FindAddress geocodeWithParameters] m_locatorTask->geocodeWithParametersAsync(address, m_geocodeParameters).then(this, [this](const QList<GeocodeResult>& geocodeResults) { if (geocodeResults.isEmpty()) return;
m_graphic->setGeometry(geocodeResults.at(0).displayLocation()); m_graphic->attributes()->setAttributesMap(geocodeResults.at(0).attributes()); constexpr double scale = 8000.0; m_mapView->setViewpointCenterAsync(geocodeResults.at(0).extent().center(), scale); }); //! [FindAddress geocodeWithParameters]}
void FindAddress::clearGraphics(){ m_graphic->setGeometry(Point());}// [WriteFile Name=FindAddress, 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]
#ifndef FIND_ADDRESS_H#define FIND_ADDRESS_H
// ArcGIS Maps SDK headers#include "GeocodeParameters.h"
// Qt headers#include <QQuickItem>
namespace Esri::ArcGISRuntime{ class Map; class MapQuickView; class GraphicsOverlay; class Graphic; class LocatorTask;}
class FindAddress : public QQuickItem{ Q_OBJECT
public: explicit FindAddress(QQuickItem* parent = nullptr); ~FindAddress() override;
void componentComplete() override; static void init(); Q_INVOKABLE void geocodeAddress(const QString& address); Q_INVOKABLE void clearGraphics();
signals: void hideCallout(); void showCallout();
private: void connectSignals();
private: Esri::ArcGISRuntime::Map* m_map = nullptr; Esri::ArcGISRuntime::MapQuickView* m_mapView = nullptr; Esri::ArcGISRuntime::GraphicsOverlay* m_graphicsOverlay = nullptr; Esri::ArcGISRuntime::LocatorTask* m_locatorTask = nullptr; Esri::ArcGISRuntime::GeocodeParameters m_geocodeParameters; Esri::ArcGISRuntime::Graphic* m_graphic = nullptr;};
#endif // FIND_ADDRESS_H// [WriteFile Name=FindAddress, 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]
import QtQuickimport QtQuick.Controlsimport QtQuick.Layoutsimport Esri.Samplesimport Esri.ArcGISRuntime.Toolkit
FindAddressSample { id: findAddressSample width: 800 height: 600
// add a mapView component MapView { id: mapView anchors.fill: parent objectName: "mapView"
Component.onCompleted: { // Set the focus on MapView to initially enable keyboard navigation forceActiveFocus(); }
Callout { id: callout background: Rectangle { border.color: "lightgrey" border.width: 1 } calloutData: mapView.calloutData maxWidth: findAddressSample.width * 0.75 leaderPosition: Callout.LeaderPosition.Automatic accessoryButtonVisible: false } }
onShowCallout: { callout.showCallout(); }
onHideCallout: { if (callout.visible) callout.dismiss(); }
// search bar for geocoding Column { anchors { fill: parent margins: 10 } Rectangle { color: "#f7f8fa" border { color: "#7B7C7D" } radius: 2 width: parent.width height: childrenRect.height
GridLayout { width: parent.width columns: 3 TextField { Layout.margins: 5 Layout.fillWidth: true id: textField font.pixelSize: 14 placeholderText: "Type in an address" selectByMouse: true
Keys.onEnterPressed: geocodeAddress(); Keys.onReturnPressed: geocodeAddress();
function geocodeAddress() { findAddressSample.geocodeAddress(textField.text); suggestView.visible = false; Qt.inputMethod.hide(); } }
Rectangle { Layout.margins: 5 width: height height: textField.height color: "#f7f8fa" visible: textField.length === 0 enabled: visible Image { anchors.fill: parent source: "qrc:/Samples/Search/FindAddress/ic_menu_collapsedencircled_light_d.png" MouseArea { anchors.fill: parent onClicked: { textField.focus = true; suggestView.visible = !suggestView.visible; } } } }
Rectangle { Layout.margins: 5 width: height color: "transparent" height: textField.height visible: textField.length !== 0 enabled: visible Image { anchors.fill: parent source: "qrc:/Samples/Search/FindAddress/ic_menu_closeclear_light_d.png"
MouseArea { anchors.fill: parent onClicked: { textField.text = ""; if (callout.visible) callout.dismiss(); clearGraphics(); } } } } } }
// show a drop down of suggested locations ListView { id: suggestView height: 300 width: textField.width visible: false clip: true model: geocodeSuggestions delegate: Component { Rectangle { id: rect width: parent.width height: 25 color: "#f7f8fa"
Rectangle { anchors { top: parent.top; left: parent.left; right: parent.right; topMargin: -5 leftMargin: 20 rightMargin: 20 } color: "darkgrey" height: 1 }
Text { text: name anchors { fill: parent leftMargin: 5 }
font.pixelSize: 14 }
MouseArea { anchors.fill: parent onClicked: { textField.text = name; suggestView.visible = false; findAddressSample.geocodeAddress(name); Qt.inputMethod.hide(); } } } } } }
ListModel { id: geocodeSuggestions ListElement { name: "277 N Avenida Caballeros, Palm Springs, CA" } ListElement { name: "380 New York St, Redlands, CA 92373" } ListElement { name: "Београд" } ListElement { name: "Москва" } ListElement { name: "北京" } }}// [Legal]// Copyright 2015 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]
// sample headers#include "FindAddress.h"
// ArcGIS Maps SDK headers#include "ArcGISRuntimeEnvironment.h"
// Qt headers#include <QCommandLineParser>#include <QDir>#include <QGuiApplication>#include <QQmlEngine>#include <QQuickView>#include <QSettings>
// Other headers#include "Esri/ArcGISRuntime/Toolkit/register.h"
// Platform specific headers#ifdef Q_OS_WIN#include <Windows.h>#endif
#define STRINGIZE(x) #x#define QUOTE(x) STRINGIZE(x)
int main(int argc, char *argv[]){ Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setUseLegacyAuthentication(false); QGuiApplication app(argc, argv); app.setApplicationName(QString("FindAddress"));
// Use of ArcGIS location services, such as basemap styles, geocoding, and routing services, // requires an access token. For more information see // https://links.esri.com/arcgis-runtime-security-auth.
// The following methods grant an access token:
// 1. User authentication: Grants a temporary access token associated with a user's ArcGIS account. // To generate a token, a user logs in to the app with an ArcGIS account that is part of an // organization in ArcGIS Online or ArcGIS Enterprise.
// 2. API key authentication: Get a long-lived access token that gives your application access to // ArcGIS location services. Go to the tutorial at https://links.esri.com/create-an-api-key. // Copy the API Key access token.
const QString accessToken = QString("");
if (accessToken.isEmpty()) { qWarning() << "Use of ArcGIS location services, such as the basemap styles service, requires" << "you to authenticate with an ArcGIS account or set the API Key property."; } else { Esri::ArcGISRuntime::ArcGISRuntimeEnvironment::setApiKey(accessToken); }
// Initialize the sample FindAddress::init();
// Initialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView);
// Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml"));
QString arcGISRuntimeImportPath = QUOTE(ARCGIS_RUNTIME_IMPORT_PATH);
#if defined(LINUX_PLATFORM_REPLACEMENT) // on some linux platforms the string 'linux' is replaced with 1 // fix the replacement paths which were created QString replaceString = QUOTE(LINUX_PLATFORM_REPLACEMENT); arcGISRuntimeImportPath = arcGISRuntimeImportPath.replace(replaceString, "linux", Qt::CaseSensitive); #endif
// Add the Runtime and Extras path view.engine()->addImportPath(arcGISRuntimeImportPath);
Esri::ArcGISRuntime::Toolkit::registerComponents(*(view.engine()));
// Set the source view.setSource(QUrl("qrc:/Samples/Search/FindAddress/FindAddress.qml"));
view.show();
return app.exec();}