Identify

Download Sample Viewer

Description

This application shows how to perform the Identify task, using local data. An IdentifyTask is created using a local dynamic layer (ArcGISLocalDynamicMapServiceLayer) and in this case the task is executed synchronously on the local server.

Code snippet


    IdentifyParameters identifyparam = new IdentifyParameters();
    identifyparam.setGeometry(geometry);
    identifyparam.setMapExtent(map.getExtent());
    identifyparam.setSpatialReference(map.getSpatialReference());
    identifyparam.setMapHeight(map.getHeight());
    identifyparam.setMapWidth(map.getWidth());
    identifyparam.setLayerMode(IdentifyParameters.VISIBLE_LAYERS);
    identifyparam.setDPI(ArcGISRuntime.getDPI());
    IdentifyTask task = new IdentifyTask(dynamicLayer.getUrl());
    try {
        IdentifyResult[] results = task.execute(identifyparam);
        displayResults(results);
    } 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.io.File;

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.client.local.ArcGISLocalDynamicMapServiceLayer;
import com.esri.toolkit.utilities.ResultPanel;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.Point;
import com.esri.core.tasks.identify.IdentifyParameters;
import com.esri.core.tasks.identify.IdentifyResult;
import com.esri.core.tasks.identify.IdentifyTask;
import com.esri.map.JMap;
import com.esri.map.LayerInitializeCompleteEvent;
import com.esri.map.LayerInitializeCompleteListener;
import com.esri.map.MapOverlay;
import com.esri.runtime.ArcGISRuntime;

/***
 * This application shows how to perform the Identify task.
 * An <code>IdentifyTask</code> is created using a local dynamic layer
 * (<code>ArcGISLocalDynamicMapServiceLayer</code>) and in this
 * case the task is executed synchronously on the local server.
 */
public class LocalIdentify {

  private static String FSP = System.getProperty("file.separator");

  // components
  private JMap map;
  private ArcGISLocalDynamicMapServiceLayer dynamicLayer;
  private JComponent contentPane;
  private ResultPanel resultPanel;

  // UI constants for sizing
  private static final int PANEL_WIDTH = 250;

  // ------------------------------------------------------------------------
  // Constructor
  // ------------------------------------------------------------------------
  public LocalIdentify() {

  }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * Perform the Identify task on the geometry - the clicked point, in this
   * case.
   * @param geometry
   */
  private void identify(Geometry geometry) {
    IdentifyParameters identifyparam = new IdentifyParameters();
    identifyparam.setGeometry(geometry);
    identifyparam.setMapExtent(map.getExtent());
    identifyparam.setSpatialReference(map.getSpatialReference());
    identifyparam.setMapHeight(map.getHeight());
    identifyparam.setMapWidth(map.getWidth());
    identifyparam.setLayerMode(IdentifyParameters.VISIBLE_LAYERS);
    identifyparam.setDPI(ArcGISRuntime.getDPI());

    IdentifyTask task = new IdentifyTask(dynamicLayer.getUrl());
    try {
      IdentifyResult[] results = task.execute(identifyparam);
      displayResults(results);
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(contentPane, wrap(e.getMessage()));
    }
  }

  private void displayResults(IdentifyResult[] results) {

    // write the new title for our query results panel
    resultPanel.setTitle(results.length + " Identify result" + (results.length == 1 ? "" : "s")+":");

    // write the results to our text area
    StringBuilder text = new StringBuilder();

    for (int i = 0; i < results.length; i++) {
      IdentifyResult result = results[i];

      String resultString = result.getAttributes().get(
          result.getDisplayFieldName())
          + " (" + result.getLayerName() + ")";
      text.append(resultString + "\n");
    }
    resultPanel.setContent(text.toString());
    resultPanel.setVisible(true);
  }

  /**
   * Map overlay to get the clicked point and call the
   * identify method on it.
   */
  private class MouseClickedOverlay extends MapOverlay {
    private static final long serialVersionUID = 1L;

    @Override
    public void onMouseClicked(MouseEvent arg0) {
      try {
        Point mapPoint = map.toMapPoint(arg0.getX(), arg0.getY());
        identify(mapPoint);
      } finally {
        super.onMouseClicked(arg0);
      }
    }
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          LocalIdentify localIdentifyApp = new LocalIdentify();
          // create the UI, including the map, for the application.
          JFrame appWindow = localIdentifyApp.createWindow();
          appWindow.add(localIdentifyApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------
  public JComponent createUI() {

    contentPane = createContentPane();

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

    // result panel
    resultPanel = new ResultPanel();
    resultPanel.setLocation(10, description.getHeight() + 20);
    contentPane.add(resultPanel);

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

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates the map.
   * @return a map.
   */
  private JMap createMap() {

    final JMap jMap = new JMap();

    // create and add the dynamic layer
    dynamicLayer = new ArcGISLocalDynamicMapServiceLayer(
        getPathSampleData() + FSP + "mpks" + FSP + "USCitiesStates_Lambert_Conformal_Conic.mpk");
    jMap.getLayers().add(dynamicLayer);
    
    dynamicLayer
        .addLayerInitializeCompleteListener(new LayerInitializeCompleteListener() {

          @Override
          public void layerInitializeComplete(LayerInitializeCompleteEvent e) {
            if (e.getID() == LayerInitializeCompleteEvent.LOCALLAYERCREATE_ERROR) {
              String errMsg = "Failed to initialize due to "
                  + dynamicLayer.getInitializationError();
              JOptionPane.showMessageDialog(jMap, wrap(errMsg), "",
                  JOptionPane.ERROR_MESSAGE);
            }

          }
        });

    // listen to mouse events for the Identify task on the clicked features
    jMap.addMapOverlay(new MouseClickedOverlay());

    return jMap;
  }

  /**
   * Creates a description for this application.
   * @return description
   */
  private JPanel createDescription() {
    JPanel descriptionContainer = new JPanel();
    descriptionContainer.setLayout(new BoxLayout(descriptionContainer, 0));
    descriptionContainer.setSize(PANEL_WIDTH, 85);
    JTextArea description = new JTextArea(
        "Click on the map to perform the Identify task on the clicked point. " +
        "The clicked features will be displayed in a result panel.");
    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;
  }

  /**
   * Creates a window.
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Local Identify 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);
        map.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;
  }

  private String getPathSampleData() {
    String dataPath = null;
    String javaPath = ArcGISRuntime.getInstallDirectory();
    if (javaPath != null) {
      if (!(javaPath.endsWith("/") || javaPath.endsWith("\\"))){
        javaPath += FSP;
      }
      dataPath = javaPath + "sdk" + FSP + "samples" + FSP + "data" + FSP;
    }
    File dataFile = new File(dataPath);
    if (!dataFile.exists()) { 
      dataPath = ".." + FSP + "data" + FSP;
    }
    return dataPath;
  }
  
  private String wrap(String str) {
    // create a HTML string that wraps text when longer
    return "<html><p style='width:200px;'>" + str + "</html>";
  }
}
Feedback on this topic?