HOW TO

Add a selection tool to the ArcGIS Server application built with the Java ADF MapViewer template

Last Published: April 26, 2020

Summary

To use a selection tool in a MapViewer template Web application, it is necessary to set the selected layer to the AGSSelection object as shown below:

AGSSelection selection = (AGSSelection)agsContext.getAttribute(AGSSelection.WEB_CONTEXT_ATTRIBUTE_NAME);
selection.setSelectedLayerId(layerId);

Instructions provided describe step by step how to add the selection tool to the Map Viewer template created with ArcGIS Server Java ADF.

Procedure

  1. Use the arcgisant tool to create a Web application named SelectionTest using the MapViewer template.
See "CREATING YOUR FIRST WEB APPLICATION WITH A TEMPLATE" section under "Developing Web applications with Java" chapter in ArcGIS Server Administrator and Developer Guide for instructions on creating a Web application using arcgisant tool.
  1. Verify that the application can be viewed successfully before proceeding to the next step.
  2. Create a new temporary folder named agstemp in any convenient location.
    Copy SelectionTest folder from <ArcGIS Installation Directory>\DeveloperKit\Templates\Java\build directory to agstemp directory.
  3. Create these new folders under agstemp folder:
  • ant
  • build
  • src
  1. Create a file named build.xml in agstemp/ant folder with this content.
    <project default="build" basedir="../" name="ags" >
    <!-- ========================================= -->
    <!-- load environment variables -->
    <!-- ========================================= -->
    <property environment="env"/>
    <property name="devkit.home" value="${env.AGSDEVKITHOME}" />
    <property name="arcgisant.home" value="${devkit.home}/tools/ant"/>
    <!-- ========================================= -->
    <!-- library dependency settings -->
    <!-- ========================================= -->
    <property name="arcgis.dir"
      location="${devkit.home}/Templates/Java/WEB-INF/lib"/>
    <!-- jar file mappings -->
    <property name="jintegra.jar" location="${arcgis.dir}/jintegra.jar"/>
    <property name="arcobjects.jar"
      location="${arcgis.dir}/arcobjects.jar"/>
    <property name="arcgis_webcatalog.jar"
      location="${arcgis.dir}/arcgis_webcatalog.jar"/>
    <!-- Project settings -->
    <property name="project.distname" value="SelectionTest"/>
    <!-- current project paths -->
    <property file="${basedir}/ant/build.properties"/>
    <property name="webroot.dir" value="${basedir}/${project.distname}"/>
    <property name="webinf.dir" value="${webroot.dir}/WEB-INF"/>
    <property name="src.dir" value="${basedir}/src"/>
    <property name="build.dir" value="build"/>
    <path id="arcgis.classpath">
      <fileset dir="${arcgis.dir}">
        <include name="*.jar" />
      </fileset>
    </path>
    <!-- Check timestamp on files -->
    <target name="prepare">
      <tstamp/>
    </target>
    <!-- Copy any resource or configuration files -->
    <target name="resources"
         description="Copy any resource or configuration files">
      <copy todir="${webinf.dir}/classes" includeEmptyDirs="no">
       <fileset dir="${src.dir}">
        <patternset>
         <include name="**/*.conf"/>
         <include name="**/*.properties"/>
         <include name="**/*.xml"/>
        </patternset>
       </fileset>
      </copy>
    </target>
    <!-- compile-->
    <target name="compile" depends="prepare,resources"
        description="Compile the project classes">
      <javac srcdir="${src.dir}" destdir="${webinf.dir}/classes">
       <classpath refid="arcgis.classpath"/>
      </javac>
    </target>
    <!-- Remove existing compiled classes -->
    <target name="clean"
        description="Remove classes directory for clean build">
      <delete dir="${webinf.dir}/classes"/>
      <mkdir dir="${webinf.dir}/classes"/>
    </target>
    <!-- Build the project -->
    <target name="build1" description="Build the project"
        depends="prepare,compile"/>
    <target name="rebuild" description="Rebuild the project"
        depends="clean,prepare,compile"/>
    <!-- Create war file -->
    <target name="build" depends="build1"
        description="Create the war file for deployment">
      <mkdir dir="${build.dir}"/>
      <war basedir="${webroot.dir}"
        warfile="${build.dir}/${project.distname}.war"
          webxml="${webinf.dir}/web.xml">
       <exclude name="WEB-INF/${build.dir}/**"/>
       <exclude name="WEB-INF/src/**"/>
       <exclude name="WEB-INF/web.xml"/>
      </war>
     </target>
    </project>
  2. Create this path under agstemp/src folder: com/esri/arcgis/webcontrols/samples
  3. Create a file named AGSSelectionLayer.java in the samples folder with this code:
    package com.esri.arcgis.webcontrols.samples;
    import com.esri.arcgis.webcontrols.faces.event.*;
    import com.esri.arcgis.webcontrols.data.*;
    import com.esri.arcgis.webcontrols.ags.data.*;
    import java.util.*;
    import javax.faces.component.UIData;
    import javax.faces.model.SelectItem;
    import java.util.logging.*;
    import com.esri.arcgis.geodatabase.*;
    
    public class AGSSelectionLayer implements
          WebContextInitialize, WebContextObserver{
      private static Logger logger =
            Logger.getLogger(AGSSelectionLayer.class.getName());
      private AGSWebContext agsContext;
      private String mapName;
      private int layerId = 0;
      public void init(WebContext agsContext) {
          if(agsContext == null || ! (agsContext instanceof AGSWebContext))
            throw new IllegalArgumentException
              ("WebContext is null or is not an instance of AGSWebContext.");
          this.agsContext = (AGSWebContext)agsContext;
          setLayerId(((Integer)((SelectItem)
             ((AGSWebMap)agsContext.getWebMap()).getFeatureLayers().get(0))
                .getValue()).intValue());
      }
    
      public void update(WebContext context, Object arg) {
        if(arg == null || arg != AGSRefreshId.DATA_FRAME_CHANGED) return;
        AGSWebMap agsMap = ((AGSWebMap)agsContext.getWebMap());
        this.mapName = agsMap.getFocusMapName();
        setLayerId(((Integer)((SelectItem)
          agsMap.getFeatureLayers().get(0))
          .getValue()).intValue());
      }
    
      public int getLayerId() {
        return layerId;
      }
    
      public void setLayerId(int layerId) {
        this.layerId = layerId;
        AGSSelection selection = (AGSSelection)agsContext
             .getAttribute(AGSSelection.WEB_CONTEXT_ATTRIBUTE_NAME);
        selection.setSelectedLayerId(layerId);
      }
    
      public void clearResults() {
        try {
          com.esri.arcgis.carto.ILayerDescriptions layerDescs =
              ((AGSWebMap)agsContext.getWebMap()).
                getFocusMapDescription().getLayerDescriptions();
          for(int i = 0; i < layerDescs.getCount(); ++i)
              layerDescs.getElement(i).setSelectionFeatures(null);
        } catch(Exception _) {
           logger.log(Level.WARNING, "Unable to deselect features.", _);
        }
        agsContext.refresh(AGSRefreshId.MAP_OPERATION);
      }
    }
  4. Go to agstemp/SelectionTest/WEB-INF/classes folder and open managed_context_attributes.xml file in a text editor. Add a new managed-context-attribute as shown below:
    <managed-context-attribute>
    	<name>esriAGSSelectionLayer</name>
    	<attribute-class>com.esri.arcgis.webcontrols.samples.AGSSelectionLayer</attribute-class>
    	<description>Selection Layer</description>
    </managed-context-attribute>
  5. Open mapviewer.jsp file from agstemp/SelectionTest folder and find the IMG tag for identify tool. Add the following code after the identify tool:
    Note:
    This adds a drop-down list of FeatureLayers, a Select tool, and a button to clear selection.
    <td>
           Select From:
        </td>
        <td>
    	 <jsfh:selectOneMenu onchange="this.form.submit();" 
    		value="#{sessionScope['mapContext'].attributes['esriAGSSelectionLayer'].layerId}">
    	  <jsfc:selectItems value="#{sessionScope['mapContext'].webMap.featureLayers}"/>
           </jsfh:selectOneMenu> 
        </td>
        <td>      	      	
    	<IMG id="imgSelection" name="imgSelection" src="images/polygon.gif" alt="select" title="Select"
    		onmouseover="this.src='images/polygonU.gif'" 
    		onmousedown="this.src='images/polygonD.gif';MapDragRectangle('Map0', 'Selection');HighlightTool('Selection');"
    		onmouseout="ButtonOut('imgSelection', 'Map0', 'Selection', 'images/polygon.gif', 'images/polygonD.gif')">
        </td>
        <td>
    	<jsfh:commandButton id="cmdClear" image="images/cancel.gif" 
    		onmousedown="this.src='images/cancelD.gif'" 
    		onmouseover="this.src='images/cancelU.gif'" 
    		onmouseout="this.src='images/cancel.gif'" 
    		title="Clear Selection" alt="Clear Selection" 
    		action="#{sessionScope['mapContext'].attributes['esriAGSSelectionLayer'].clearResults}" />
        </td>
    
  6. Open the templates.js file in a text editor from agstemp/SelectionTest/js folder and find HighlightTool function. Modify this function as shown below to include the Selection tool.
                       function HighlightTool(tool)
    			{
    				if ((tool!=null) && (tool!=""))
    				{
    					document.images["imgZoomIn"].src = "images/zoomin.gif";
    					document.images["imgZoomOut"].src = "images/zoomout.gif";
    					document.images["imgPan"].src = "images/pan.gif";
    					document.images["imgIdentify"].src = "images/identify.gif";
    					document.images["imgSelection"].src = "images/polygon.gif";
    					switch (tool)
    					{
    						case "ZoomIn":
    							document.images["imgZoomIn"].src = "images/zoominD.gif";
    							break;
    						case "ZoomOut":
    							document.images["imgZoomOut"].src = "images/zoomoutD.gif";
    							break;
    						case "Pan":
    							document.images["imgPan"].src = "images/panD.gif";
    							break;
    						case "Identify":
    							document.images["imgIdentify"].src = "images/identifyD.gif";
    							break;
    						case "Selection":
    							document.images["imgSelection"].src = "images/polygonD.gif";
    							break;
    						default:
    					}
    				}
    		}
    
  7. Open command prompt and CD to agstemp/SelectionTest/ant folder. Run this command: arcgisant build.
  8. Verify that the SelectionTest.war file is created in agstemp/build folder. Copy this file back to the <ArcGIS Installation Directory>\DeveloperKit\Templates\Java\build directory.
  9. Copy agstemp/SelectionTest folder back to the <ArcGIS Installation Directory>\DeveloperKit\Templates\Java\build directory.
  10. Use arcgisant tool to deploy the Web application.
    See "CREATING YOUR FIRST WEB APPLICATION WITH A TEMPLATE" section under "Developing Web applications with Java" chapter in ArcGIS Server Administrator and Developer Guide for instructions on deploying a Web application using arcgisant tool.
  11. Test the Web application.

Article ID:000007966

Software:
  • ArcGIS Server

Get help from ArcGIS experts

Contact technical support

Download the Esri Support App

Go to download options

Discover more on this topic