Find

Download Sample Viewer

Description

This application demonstrates executing a FindTask, adding the results to a table, and zooming to a selected result.

Code snippet


    FindParameters params = new FindParameters();
    params.setSearchText(findText.getText())
    params.setLayerIds(new int[] { 0, 1, 2 });
    params.setOutputSpatialRef(map.getSpatialReference());

    FindTask task = new FindTask(URL_STATES);

    try {
        FindResult[] results = task.execute(params);
        // process / display the 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.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.Geometry.Type;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.tasks.ags.find.FindParameters;
import com.esri.core.tasks.ags.find.FindResult;
import com.esri.core.tasks.ags.find.FindTask;
import com.esri.map.ArcGISDynamicMapServiceLayer;
import com.esri.map.ArcGISTiledMapServiceLayer;
import com.esri.map.GraphicsLayer;
import com.esri.map.JMap;

/***
 * This sample demonstrates executing a FindTask, adding the results to 
 * a table, and zooming to a selected result.
 */
public class FindApp {
  // resources
  final String URL_USA_TOPO = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer";
  final String URL_STATES = "http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StatesCitiesRivers_USA/MapServer";

  // UI related
  JTextField findText = new JTextField("Colorado");
  DefaultTableModel tblModelStateInfo;

  // JMap
  private JMap map;

  // our graphics layer for highlighted geometries
  private GraphicsLayer graphicsLayer;

  // for zooming to a buffered geometry
  private static final double BUFFER_DISTANCE = 500000; // 500 km

  // results of the Find task execution
  List<FindResult> findResults = null;

  // ------------------------------------------------------------------------
  // Constructors
  // ------------------------------------------------------------------------
  public FindApp() {
  }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  /**
   * This method creates and executes the FindTask to find the input text
   *
   */
  private void onFind() {
    tblModelStateInfo.setRowCount(0);

    // return if input text is not valid
    if (findText.getText() == null || findText.getText().isEmpty()) {
      return;
    }

    // -----------------------------------------------------------------------------------------
    // Find task to find the search string specified by the user in all attributes of dynamic
    // service
    // -----------------------------------------------------------------------------------------
    // create a Find task.
    FindParameters params = new FindParameters();
    params.setSearchText(findText.getText());
    params.setLayerIds(new int[] { 0, 1, 2 });
    params.setOutputSpatialRef(map.getSpatialReference());

    // execute the find task
    FindTask task = new FindTask(URL_STATES);
    try {
      findResults = task.execute(params);

      if (findResults == null){
        return;
      }

      for (FindResult result : findResults) {
        tblModelStateInfo.addRow(new Object[] {
            result.getAttributes().get(result.getDisplayFieldName()),
            Integer.valueOf(result.getLayerId()), result.getLayerName(),
            result.getFoundFieldName(), result.getValue() });
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // ------------------------------------------------------------------------
  // Static methods
  // ------------------------------------------------------------------------
  /**
   * Starting point of this application.
   *
   * @param args
   *            arguments to this application.
   */
  public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        try {
          // instance of this application
          FindApp findApp = new FindApp();

          // create the UI, including the map, for the application.
          JFrame appWindow = findApp.createWindow();
          appWindow.add(findApp.createUI());
          appWindow.setVisible(true);
        } catch (Exception e) {
          // on any error, display the stack trace.
          e.printStackTrace();
        }
      }
    });
  }

  // ------------------------------------------------------------------------
  // Public methods
  // ------------------------------------------------------------------------

  /**
   * Creates and displays the UI, including the map, for this application.
   */
  public JComponent createUI() throws Exception {

    // content pane
    JComponent contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout(1, 0));

    // map
    map = createMap();

    // input text and find button
    JLabel findLabel = new JLabel("Find ");
    findLabel.setForeground(Color.WHITE);
    findLabel.setFont(new Font(findLabel.getFont().getName(), findLabel
        .getFont().getStyle(), 14));
    findText.setFont(new Font(findLabel.getFont().getName(), findLabel
        .getFont().getStyle(), 14));
    findText.setMinimumSize(new Dimension(150, 25));
    findText.setMaximumSize(new Dimension(150, 25));
    findText.setColumns(10);
    JLabel remainderLabel = new JLabel(
        " in the attributes of State, Rivers and Cities.");
    remainderLabel.setForeground(Color.WHITE);
    remainderLabel.setFont(new Font(findLabel.getFont().getName(),
        findLabel.getFont().getStyle(), 14));
    JButton findButton = new JButton("Find");
    findButton.setFont(new Font(findLabel.getFont().getName(), findLabel
        .getFont().getStyle(), 14));
    findButton.addActionListener(new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent arg0) {
        onFind();
      }
    });

    // scrollable-table to display the FindResult information
    tblModelStateInfo = new DefaultTableModel() {
      private static final long serialVersionUID = 1L;

      @Override
      public boolean isCellEditable(int rowIndex, int mColIndex) {
        return false;
      }
    };
    // add the column headers
    tblModelStateInfo.addColumn("Display Field");
    tblModelStateInfo.addColumn("Layer Id");
    tblModelStateInfo.addColumn("Layer Name");
    tblModelStateInfo.addColumn("Found Field");
    tblModelStateInfo.addColumn("Found Field Value");

    final JTable stateInfoTable = new JTable(tblModelStateInfo);
    JScrollPane tblStateInfoScrollable = new JScrollPane(stateInfoTable);
    stateInfoTable.getSelectionModel().addListSelectionListener(
        new ListSelectionListener() {
          @Override
          public void valueChanged(ListSelectionEvent e) {
            int rowId = stateInfoTable.getSelectedRow();
            if (0 <= rowId && rowId < findResults.size()) {
              highlightGeometry(findResults.get(rowId)
                  .getGeometryType(), findResults.get(rowId)
                  .getGeometry());
            }
          }
        });

    //panels to contain input text and find button
    JPanel topPanel = new JPanel();
    topPanel.setBackground(Color.BLACK);
    topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
    topPanel.add(Box.createHorizontalGlue());
    topPanel.add(findLabel);
    topPanel.add(findText);
    topPanel.add(remainderLabel);
    topPanel.add(findButton);
    topPanel.add(Box.createHorizontalGlue());

    //panel to contain find results
    JPanel bottomPanel = new JPanel();
    bottomPanel.setLayout(new BorderLayout());
    bottomPanel.add(tblStateInfoScrollable, BorderLayout.CENTER);
    bottomPanel.setPreferredSize(new Dimension(600, 150));

    contentPane.add(topPanel, BorderLayout.NORTH);
    contentPane.add(map, BorderLayout.CENTER);
    contentPane.add(bottomPanel, BorderLayout.SOUTH);

    return contentPane;
  }

  // ------------------------------------------------------------------------
  // Private methods
  // ------------------------------------------------------------------------
  /**
   * Creates a window.
   *
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Find 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 map.
   *
   * @return a map.
   */
  private JMap createMap() throws Exception {
    final JMap jMap = new JMap();
    // -----------------------------------------------------------------------------------------
    // Base Layer - with US topology, focus on U.S by default
    // -----------------------------------------------------------------------------------------
    final ArcGISTiledMapServiceLayer baseLayer = new ArcGISTiledMapServiceLayer(
        URL_USA_TOPO);
    jMap.setExtent(new Envelope(-15000000, 2000000, -7000000, 8000000));

    jMap.getLayers().add(baseLayer);

    // -----------------------------------------------------------------------------------------
    // Dynamic Layer - US Cities and States that we will search
    // -----------------------------------------------------------------------------------------
    final ArcGISDynamicMapServiceLayer layer = new ArcGISDynamicMapServiceLayer(
        URL_STATES);
    layer.setOpacity(0.6f);
    jMap.getLayers().add(layer);

    // -----------------------------------------------------------------------------------------
    // Graphics Layer - to highlight a selected feature
    // -----------------------------------------------------------------------------------------
    graphicsLayer = new GraphicsLayer();
    jMap.getLayers().add(graphicsLayer);

    return jMap;
  }

  /**
   * Display a geometry on the map for the selected table row
   *
   * @param geometryType
   * @param geometry
   */
  private void highlightGeometry(Type geometryType, Geometry geometry) {
    if (geometryType == null || geometry == null) {
      return;
    }

    // -----------------------------------------------------------------------------------------
    // Add a graphic for the selected feature to the graphics layer
    // -----------------------------------------------------------------------------------------
    graphicsLayer.removeAll();
    switch (geometryType) {
      case POINT:
        graphicsLayer.addGraphic(new Graphic(geometry,
            new SimpleMarkerSymbol(Color.RED, 8,
                SimpleMarkerSymbol.Style.DIAMOND)));
        break;
      case POLYLINE:
        graphicsLayer.addGraphic(new Graphic(geometry,
            new SimpleLineSymbol(Color.RED, 4,
                SimpleLineSymbol.Style.SOLID)));
        break;
      case POLYGON:
        graphicsLayer.addGraphic(new Graphic(geometry,
            new SimpleFillSymbol(Color.RED)));
        break;
      default:
        break;
    }

    // -----------------------------------------------------------------------------------------
    // Zoom to the highlighted graphic
    // -----------------------------------------------------------------------------------------
    Geometry geometryForZoom = GeometryEngine.buffer(geometry,
        map.getSpatialReference(), BUFFER_DISTANCE, map
        .getSpatialReference().getUnit());
    map.zoomTo(geometryForZoom);
  }

}
Feedback on this topic?