Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for Java

Reverse geocoding

Download Sample Viewer

Description

This application uses an online Geocoding Server to convert a location on the map to an address. A Locator is created from the URL of the service, and the locationToAddress method is used to do the reverse geocoding.

Code snippet


    Point mapPoint = map.toMapPoint(clickedPoint.getX(), clickedPoint.getY());
    Locator locator = Locator.createOnlineLocator(
        "http://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Streets_US/GeocodeServer");
    LocatorReverseGeocodeResult reverseResult;
    try {
        reverseResult = locator.reverseGeocode(mapPoint, 30, 
        map.getSpatialReference(), map.getSpatialReference());
        // do something with the result, for example displaying the found address
        // ...
    } catch (Exception e) {
        // handle the exception
    }
  

Sample Code

/* Copyright 2014 Esri

All rights reserved under the copyright laws of the United States
and applicable international laws, treaties, and conventions.

You may freely redistribute and use this sample code, with or
without modification, provided you include the original copyright
notice and use restrictions.

See the use restrictions.*/
package com.esri.client.samples.search;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.tasks.geocode.Locator;
import com.esri.core.tasks.geocode.LocatorReverseGeocodeResult;
import com.esri.map.ArcGISTiledMapServiceLayer;
import com.esri.map.GraphicsLayer;
import com.esri.map.JMap;
import com.esri.map.MapOverlay;
import com.esri.map.MapTip;

/***
 * This sample shows how to perform reverse geocoding.  To use the sample,
 * double click on the map along a street and a marker will be set at this
 * location with the result of the reverse geocoding displayed in a
 * {@link MapTip}. Hover over a marker to display its address in
 * a MapTip.
 * <p>
 * An online locator is created once using the URL to an online geocode 
 * service, then re-used whenever the user clicks on the map to 
 * reverse-geocode the clicked point. In this sample the reverse geocoding 
 * is performed synchronously for simplicity.
 *
 */
public class LocationToAddress extends MapOverlay {

  private static final long serialVersionUID = 1L;
  private JComponent contentPane;
  private JMap map;
  private GraphicsLayer addressGraphics;
  private PictureMarkerSymbol symPoint;
  private Locator locator;

  //------------------------------------------------------------------------
  // Constructor
  //------------------------------------------------------------------------
  public LocationToAddress() {
    symPoint = new PictureMarkerSymbol(
        "http://static.arcgis.com/images/Symbols/Basic/RedShinyPin.png");
    symPoint.setSize(40, 40);
    symPoint.setOffsetY(20.0f);
  }

  //------------------------------------------------------------------------
  // Core functionality
  //------------------------------------------------------------------------
  /**
   * Add a marker symbol and performs reverse geocoding when the user double
   * clicks a point on the map.
   */
  @Override
  public void onMouseClicked(MouseEvent event) {
    // on double-click, perform the reverse geocoding for clicked point
    if (event.getClickCount() == 2) {

      Point mapPoint = map.toMapPoint(event.getX(), event.getY());
      LocatorReverseGeocodeResult reverseResult;

      try {
        // do the reverse geocoding using the locator created
        reverseResult =  locator.reverseGeocode(mapPoint, 30, 
            map.getSpatialReference(), map.getSpatialReference());

        // create and populate attribute map for map tip
        Map<String, Object> attributes = new HashMap<>();
        for (Entry<String, String> entry : reverseResult.getAddressFields().entrySet()) {
          attributes.put(entry.getKey(), entry.getValue());
        }

        // create a graphic at this location
        Graphic addressGraphic = new Graphic(
            reverseResult.getLocation(),symPoint, attributes);
        addressGraphics.addGraphic(addressGraphic);
      }
      catch (Exception e) {
        JOptionPane
        .showMessageDialog(contentPane,
            "Unable to determine an address. Try selecting a location closer to a street.");
      }
    }
  }

  /**
   * Creates a MapTip to display the address fields when a marker is
   * placed on the map in the graphics layer.
   */
  private void addMapTip() {
    // create a MapTip for the graphics layer to show found address
    // the field names used as keys need to exactly match fields from the Geocode Service used 
    LinkedHashMap<String, String> displayFields = new LinkedHashMap<>();
    displayFields.put("Address", "Address: ");
    displayFields.put("City", "City: ");
    displayFields.put("Region", "State: ");
    displayFields.put("Postal", "ZIP: ");
    addressGraphics.setMapTip(new MapTip(displayFields));
  }

  //------------------------------------------------------------------------
  // Static methods
  //------------------------------------------------------------------------
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          LocationToAddress locationToAddressApp = new LocationToAddress();

          // create the UI, including the map, for the application.
          JFrame appWindow = locationToAddressApp.createWindow();
          appWindow.add(locationToAddressApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    });
  }

  //------------------------------------------------------------------------
  // Public methods
  //------------------------------------------------------------------------
  public JComponent createUI() {
    // application content
    contentPane = createContentPane();

    // description
    JPanel description = createDescription();
    description.setLocation(10, 10);
    contentPane.add(description);

    // map
    map = createMap();
    contentPane.add(map);

    return contentPane;
  }

  //------------------------------------------------------------------------
  // Private methods
  //------------------------------------------------------------------------
  private JMap createMap() {

    JMap jMap = new JMap();

    ArcGISTiledMapServiceLayer baseLayer = new ArcGISTiledMapServiceLayer(
        "http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
    jMap.getLayers().add(baseLayer);

    // zoom in to street level
    jMap.setExtent(new Envelope(-13641663, 4540667, -13622897, 4553183));

    // create a graphics layer to show the locations found
    addressGraphics = new GraphicsLayer();
    jMap.getLayers().add(addressGraphics);

    addMapTip();

    // listen to mouse clicks to do the geocoding
    jMap.addMapOverlay(this);

    // create Locator
    locator = Locator.createOnlineLocator(
        "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

    return jMap;
  }

  /**
   * Creates a window, disposes the map and locator on application exit / window closing.
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Location to Address Application");
    window.setBounds(100, 100, 1000, 700);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.getContentPane().setLayout(new BorderLayout(0, 0));
    window.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent windowEvent) {
        super.windowClosing(windowEvent);
        if (map != null) map.dispose();
        if (locator != null) locator.dispose();
      }
    });
    return window;
  }

  /**
   * Creates a content pane.
   * @return a content pane.
   */
  private static JLayeredPane createContentPane() {
    JLayeredPane contentPane = new JLayeredPane();
    contentPane.setBounds(100, 100, 1000, 700);
    contentPane.setLayout(new BorderLayout(0, 0));
    contentPane.setVisible(true);
    return contentPane;
  }

  /**
   * Creates a description for this application.
   * @return description
   */
  private JPanel createDescription() {
    JPanel descriptionContainer = new JPanel();
    descriptionContainer.setLayout(new BoxLayout(descriptionContainer, 0));
    descriptionContainer.setSize(260, 115);
    JTextArea description = new JTextArea(
        "Double-click on the map to set a marker at a location and to find " +
        "the address of the location via reverse-geocoding. The address of the " +
        "location will be displayed in a MapTip.  Hover over a " +
        "marker to display its address information.");
    description.setFont(new Font("Verdana", Font.PLAIN, 11));
    description.setForeground(Color.WHITE);
    description.setBackground(new Color(0, 0, 0, 180));
    description.setEditable(false);
    description.setLineWrap(true);
    description.setWrapStyleWord(true);
    description.setBorder(BorderFactory.createEmptyBorder(5,10,5,5));
    descriptionContainer.add(description);
    descriptionContainer.setBackground(new Color(0, 0, 0, 0));
    descriptionContainer.setBorder(new LineBorder(Color.BLACK, 3, false));
    return descriptionContainer;
  }
}
Feedback on this topic?