Local spatial query

Download Sample Viewer

Description

This application shows how to perform a spatial query locally. A QueryTask is created using a local dynamic layer (ArcGISLocalDynamicMapServiceLayer) and the task is executed asynchronously on the Local Server.

Code snippet


    // query for polygons that have any spatial relationship with the supplied geometry
    Query query = new Query();
    query.setGeometry(geometry);
    query.setInSpatialReference(map.getSpatialReference());
    query.setOutFields(new String[] { "STATE_NAME", "POP2000" });
    query.setReturnGeometry(true);
    QueryTask task = new QueryTask(dynamicLayer.getUrl() + "/2");
    task.executeAsync(query, new CallbackListener<FeatureSet>() {
        @Override
        public void onError(Throwable e) {
            // handle the error
        }
        @Override
            public void onCallback(FeatureSet objs) {
                // do something with the result feature set
           }
        });
    }
  

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.Iterator;

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.map.CallbackListener;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
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 a spatial query locally.
 * A <code>QueryTask</code> is created using a local dynamic layer
 * (<code>ArcGISLocalDynamicMapServiceLayer</code>) and the task
 * is executed asynchronously on the Local Server.
 */
public class LocalSpatialQuery {

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

  // UI sizing constants
  private static final int PANEL_WIDTH = 240;

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

  // ------------------------------------------------------------------------
  // Constructor
  // ------------------------------------------------------------------------
  public LocalSpatialQuery() {

  }

  // ------------------------------------------------------------------------
  // Core functionality
  // ------------------------------------------------------------------------
  private void query(Geometry geometry) {

    // query for polygons that have any spatial relationship with the supplied point
    QueryParameters queryParams = new QueryParameters();
    queryParams.setGeometry(geometry);
    queryParams.setInSpatialReference(map.getSpatialReference());
    queryParams.setOutFields(new String[] { "STATE_NAME", "POP2000" });
    queryParams.setReturnGeometry(true);

    QueryTask task = new QueryTask(dynamicLayer.getUrl() + "/2"); // polygon layer

    // execute the query asynchronously
    task.execute(queryParams, new CallbackListener<FeatureResult>() {

      @Override
      public void onError(Throwable e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(contentPane, wrap(e.getMessage()));
      }

      @Override
      public void onCallback(FeatureResult results) {
        displayResults(results);
      }
    });
  }

  private void displayResults(final FeatureResult results) {
    SwingUtilities.invokeLater(new Runnable() {
      
      @Override
      public void run() {
        // write the new title for our query results panel
        int numResults = (int) results.featureCount();
        resultPanel.setTitle(numResults + " Spatial Query result" + (numResults == 1 ? "" : "s")+":");
        // write the results to our text area
        StringBuilder text = new StringBuilder();
        Iterator<Object> it = results.iterator();
        while (it.hasNext()) {
          Object o = it.next();
          if (o instanceof Feature) {
            Feature feature = (Feature) o;
            text.append((String) feature.getAttributes().get("STATE_NAME"));
            text.append(" (");
            text.append(feature.getAttributes().get("POP2000").toString());
            text.append(")");
          }
        }
        resultPanel.setContent(text.toString());
        resultPanel.setVisible(true);
      }
    });
  }

  /**
   * Map overlay to capture the clicked point and pass it to the
   * query method
   */
  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());
        query(mapPoint);
      } finally {
        super.onMouseClicked(arg0);
      }
    }
  }

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

          // create the UI, including the map, for the application.
          JFrame appWindow = localSpatialQueryApp.createWindow();
          appWindow.add(localSpatialQueryApp.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 results panel
    resultPanel = new ResultPanel();
    resultPanel.setBounds(10, description.getHeight() + 20, PANEL_WIDTH, 75);
    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();

    // add layers
    dynamicLayer = new ArcGISLocalDynamicMapServiceLayer(
        getPathSampleData() + "mpks" + FSP + "USCitiesStates_Lambert_Conformal_Conic.mpk");

    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);
            }
          }
        });
    
    jMap.getLayers().add(dynamicLayer);

    // listen to mouse events for the query on the clicked point
    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 a local spatial query on the clicked point. " +
        "The State name and State population of the result will be displayed.");
    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 the window for the application
   * @return a window.
   */
  private JFrame createWindow() {
    JFrame window = new JFrame("Local Spatial Query 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?