Identify DEM raster

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 the task is executed on the local server, returning results including the pixel value at the clicked point on the DEM data.

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.ALL_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 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.client.local.ArcGISLocalDynamicMapServiceLayer;
import com.esri.toolkit.utilities.ResultPanel;
import com.esri.core.geometry.Envelope;
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.ArcGISTiledMapServiceLayer;
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 on a map package 
 * containing digital elevation model (DEM) raster data. To use the sample, 
 * click on a point on the map, and if within the raster data extent, 
 * information including the elevation of the pixel at the clicked point 
 * will be returned in a result panel.
 * <p>
 * To perform the Identify operation, an <code>IdentifyTask</code> is 
 * created using a local dynamic layer (<code>ArcGISLocalDynamicMapServiceLayer</code>) 
 * and the task is executed on the local server (synchronously, in this case).
 */
public class LocalIdentifyDEM {

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

  // constants
  private static final int PANEL_WIDTH = 250;
  private static final String FSP = System.getProperty("file.separator");

  // ------------------------------------------------------------------------
  // Constructor
  // ------------------------------------------------------------------------
  public LocalIdentifyDEM() {}

  // ------------------------------------------------------------------------
  // 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.ALL_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];
      text.append("result "+(i+1)+":\n");

      // if layer id = 3 (DEM layer): show attributes including pixel value (elevation in feet)
      if (result.getLayerId() == 3) {
        for (Entry<String, Object> attribute : result.getAttributes().entrySet()) {
          text.append("   ");
          text.append(attribute.getKey());
          text.append(": ");
          text.append(attribute.getValue());
          text.append("\n");
        }
      } else {
        // other layer: show layer name, result value
        text.append("   Layer name: ");
        text.append(result.getLayerName());
        text.append("\n");
        text.append("   Value: ");
        text.append(result.getValue());
        text.append("\n");
      }
      if (i < results.length - 1) {
        text.append("\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;

    protected MouseClickedOverlay() {}

    @Override
    public void onMouseClicked(MouseEvent arg0) {
      try {

        Point mapPoint = this.getMap().toMapPoint(arg0.getX(), arg0.getY());
        identify(mapPoint);
      } finally {
        super.onMouseClicked(arg0);
      }
    }
  }

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

    final JMap jMap = new JMap();

    // add a tiled map service layer and set initial map extent
    final ArcGISTiledMapServiceLayer tiledLayer = new ArcGISTiledMapServiceLayer(
        "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer");
    jMap.getLayers().add(tiledLayer);
    jMap.setExtent(new Envelope(-8115752, 5560630, -8073362, 5519019));

    // create and add the dynamic layer
    dynamicLayer = new ArcGISLocalDynamicMapServiceLayer(
        getPathSampleData() + FSP + "mpks" + FSP + "dem_stowe.mpk");
    dynamicLayer.setOpacity(0.7f);
    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;
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          LocalIdentifyDEM localIdentifyApp = new LocalIdentifyDEM();
          // 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);

    // create map
    map = createMap();

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

    contentPane.add(map);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * 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, 80);
    JTextArea description = new JTextArea(
        "Click on the map to perform the Identify task on the clicked point. " +
        "The identify results 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 DEM Application");
    window.setBounds(0, 0, 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?