Thursday, October 27, 2005

Adding Selection tool to MapViewer template

Although the selection tool is provided in ArcGIS Server MapViewer template, it can't be used as-is unlike other tools (zoomin, identify etc.) That is because it is necessary to set the selected layer to the AGSSelection object before this tool can be used.

AGSSelection selection = (AGSSelection)

Here are the steps to implement the selection tool in the MapViewer template:

1. Use arcgisant tool to create a web application named SelectionTest using the MapViewer template.

2. Create a new project as discussed here and copy over the newly created webapplication from ArcGIS build directory to this directory. Be sure to update the build file with the new app name.

3. Under the src folder, create a folder named test.

4. Create a file named in the test folder with this content:

package test;

import com.esri.arcgis.webcontrols.faces.event.*;



import java.util.*;

import javax.faces.component.UIData;

import javax.faces.model.SelectItem;

import java.util.logging.*;

import com.esri.arcgis.geodatabase.*;

import com.esri.arcgis.carto.ILayerDescriptions;

public class AGSSelectionLayer implements

WebContextInitialize, WebContextObserver{

private static Logger logger =


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 null.");

this.agsContext = (AGSWebContext)agsContext;




public void update(WebContext context, Object arg) {

if(arg == null ||

AGSWebMap agsMap = ((AGSWebMap)

this.mapName = agsMap.getFocusMapName();




public int getLayerId() {

return layerId;


public void setLayerId(int layerId) {

this.layerId = layerId;

AGSSelection selection = (AGSSelection)agsContext




public void clearResults() {

try {

ILayerDescriptions layerDescs =



for(int i = 0; i < layerDescs.getCount(); ++i)


} catch(Exception _) {

"Unable to deselect features.",





Notice that on init method, we are calling setLayerId method and passing the first featurelayer from the collection in the wemap. setLayerId method sets the selection layer to the AGSSelection object. clearResults method clears out selection from all layers.

5. Go to webapp_name/WEB-INF/classes folder and open managed_context_attributes.xml file in a text editor. Add a new managed-context-attribute as shown below:




<description>Selection Layer</description>


6. Open mapviewer.jsp file from webapp folder and find the IMG tag for identify tool. Add the following code right after it to add a dropdown list of all FeatureLayers, a Selection tool and a button to clear selection.


Select From:



lt;jsfh:selectOneMenu onchange="this.form.submit();"


<jsfc:selectItems value="#{sessionScope['mapContext'].




<IMG id="imgSelection"
MapDragRectangle('Map0', 'Selection');
onmouseout="ButtonOut('imgSelection', 'Map0',
'Selection', 'images/polygon.gif',



<jsfh:commandButton id="cmdClear"
title="Clear Selection"
alt="Clear Selection"
attributes['esriAGSSelectionLayer'].clearResults}" />


7. Open templates.js file in a text editor from 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";


case "ZoomOut":

document.images["imgZoomOut"].src = "images/zoomoutD.gif";


case "Pan":

document.images["imgPan"].src = "images/panD.gif";


case "Identify":

document.images["imgIdentify"].src = "images/identifyD.gif";


case "Selection":

document.images["imgSelection"].src = "images/polygonD.gif";






8. Open command prompt and CD to ant folder. Run this command: arcgisant build

9. Verify that the SelectionTest.war file is created in build folder. Copy this file back to the ArcGIS Installation Directory\DeveloperKit\Templates\Java\build directory.

10. Copy the webapp folder back to the ArcGIS Installation Directory\DeveloperKit\Templates\Java\build directory.

11. Use arcgisant tool to deploy the web application.

Thursday, October 20, 2005

ANT tool for customizing ArcGIS Server application

IDE projects introduce unnecessary complication and overhead. So I typically limit the use of IDE for Java development to build classes. This way I can keep my project simple and easily managable. Ant tool can instead be used for project development and deployment. ArcGIS Server uses ant for configuration and deployment of template application. It can also be used for extending the template web applications. I use the following approach to customize the ArcGIS Server java template web applications:

1. Create a workspace folder in a convenient place in your local directory. For example: C:/Temp/AGSProjects

2. Inside the workspace folder, create the project folder. For example: C:/Temp/AGSProjects/MapProject1

3. Inside the project folder, create this folder structure:

4. Use arcgisant tool to create an ArcGIS Server java template web application. Refer to ArcGIS Server Administration and Development Guide for more information.

5. Copy the web application folder built in ArcGIS\DeveloperKit\Templates\Java\build folder to the projectfolder. (MapProject1 folder in the above example.)

6. Create a file named build.xml with the following 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"
<!-- jar file mappings -->
<property name="jintegra.jar" location="${arcgis.dir}/jintegra.jar"/>
<property name="arcobjects.jar"
<property name="arcgis_webcatalog.jar"
<!-- Project settings -->
<property name="project.distname" value="MapViewer1"/>
<!-- current project paths -->
<property file="${basedir}/ant/"/>
<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" />
<!-- Check timestamp on files -->
<target name="prepare">
<!-- 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}">
<include name="**/*.conf"/>
<include name="**/*.properties"/>
<include name="**/*.xml"/>
<!-- compile-->
<target name="compile" depends="prepare,resources"
description="Compile the project classes">
<javac srcdir="${src.dir}" destdir="${webinf.dir}/classes">
<classpath refid="arcgis.classpath"/>
<!-- Remove existing compiled classes -->
<target name="clean"
description="Remove classes directory for clean build">
<delete dir="${webinf.dir}/classes"/>
<mkdir dir="${webinf.dir}/classes"/>
<!-- Build the project -->
<target name="build1" description="Build the project"
<target name="rebuild" description="Rebuild the project"
<!-- Create war file -->
<target name="build" depends="build1"
description="Create the war file for deployment">
<mkdir dir="${build.dir}"/>
<war basedir="${webroot.dir}"
<exclude name="WEB-INF/${build.dir}/**"/>
<exclude name="WEB-INF/src/**"/>
<exclude name="WEB-INF/web.xml"/>

7. Change the value in this line in the build.xml file to the name of the web application you create above.

<property name="project.distname" value="MapViewer1"/>

8. Customize the web application as necessary.

9. Add any java source code to src folder.

10. Open command prompt and CD to ant directory in your project. Type this command to build the project:
arcgisant build

11. Verify that a war file is built in the build folder. Deploy this war file directly or copy the web application folder and the war file back to ArcGIS\DeveloperKit\Templates\Java\build folder and use arcgisant to deploy it.

You can repeat the same steps to build any other web applications. You can use the same build file but make sure to update it with the new project name as mentioned above in step 7.

Tuesday, September 27, 2005

Tutorial: Using Ajax in a JSF application - II

In part I, we have created a simple JSF application. Next we will implement Ajax into this application. This will require us to create i) a server side application to dynamically provide the data to the client and ii) client side javascript functions to request data and process the response.

Step 1: Create the servlet as a server side application.
Copy the following code and save it as in ajax/Web-Inf/classes/demo folder:

package demo;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class AjaxServlet extends HttpServlet {

private ServletConfig servletConfig = null;

public void destroy() {

servletConfig = null;


public ServletConfig getServletConfig() {

return (this.servletConfig);


public String getServletInfo() {

return (this.getClass().getName());


public void init(ServletConfig servletConfig)

throws ServletException {

this.servletConfig = servletConfig;


public void doGet(HttpServletRequest request,

HttpServletResponse response)


ServletException {

String key = (String)request.getParameter("key");

//get CountryBean object from ServletContext

CountryBean countryBean = (CountryBean)


//get list of countries

String[] countries = countryBean.getCountries();

//find matches

String matches = getMatches(countries, key);

//print it out to the client

response.setContentType("text/xml"); out=response.getWriter();




public void doPost(HttpServletRequest request,

HttpServletResponse response)


ServletException {

doGet(request, response);


private String getMatches(

String[] countries, String key){

//generate xml response

String cList = "<?xml version=\"1.0\" ";

cList += "encoding=\"UTF-8\" ?>";

cList +="<COUNTRIES>";

int count = 0;

//from countries list find first 5 matches

for(int i=0;i<countries.length;i++){



cList += "<COUNTRY name=\"" + countries[i] + "\" />";


if(count == 5) break;



cList += "<TOTALCOUNT count=\"" + count + "\" />";

cList += "</COUNTRIES>";

return cList;



In doGet method of the above code, we first get the value of "key"
parameter submitted from the client. Next, we get the JSF managed
CountryBean from which we obtain a list of countries and store
it in a String array:

CountryBean countryBean = (CountryBean)
//get list of countries
String[] countries = countryBean.getCountries();

We then call getMatches method to check for country names that start with the key string sent by the user. This is, of course, a very simple method but you can substitute it with your own advanced code.

Notice also that this method generates an XML document with a list of matching country names. Finally the XML document is sent to the client.

Step 2: Configure the Servlet
Open web.xml file from ajax/WEB-INF folder and add the custom servlet right after Faces Servlet:





Add this servlet mapping after Faces Servlet mapping:





Step 3: Add javascript code to the application

Download the script.js file from here and copy it to ajax/js folder.

Notice in the js file that the following code creates the XMLHTTPRequest object.
(Also notice the difference in the code for creating this object in IE vs Mozilla.)

var req;

//initialize the XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");

The function initPopup is responsible for turning off the autocomplete
feature of the browser. It also gets the location of the autocomplete
text-box and positions the popup element right below it. We will call
this function after the page is loaded.

The function doMouseClick is called when an item is selected in
popup list. This function sets the item value to the text box.

The functions hidePopup and showPopup simply hide and show the
popup element.

The function getQuery uses the XMLHttpRequest object and submits
the current text-box value to the AjaxServlet. Notice the path to our custom AjaxServlet configured above and how the key value is appended to the URL:
var url = "/ajax/AjaxServlet?key=" + key;

Also, notice the following line in this function:
req.onreadystatechange = processResponse;

The above line indicates that the processResponse function is called
when the response is received by the client. The processResponse
function forwards the response to parseResponse function.

The parseResponse function processes the response from the server.
Remember that the response is an XML document. So this function parses the XML document using dom parser and extracts the country names.
The country names will then be added to the popup CSS element which will then be displayed by setting its visibility to true.

The following code is required for Mozilla since it does not implement loadXML method by default.

//check if it is IE
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

//implement loadXML method for Mozilla since it is not supported
Document.prototype.loadXML = function (s) {

// parse the string to a new doc
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");

// remove all initial children
while (this.hasChildNodes())

// insert and import nodes
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));

Step 4: Reference the javascript code in JSP page

Add this line within the HEAD of jsp code:

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript" SRC="js/script.js"></SCRIPT>

Step 5: Enable ajax for input text

Modify the inputText component as follows:

<h:inputText id="autoText" onblur="hidePopup()" onfocus="getQuery(this.value)" onkeyup="getQuery(this.value)" value="#SelectedCountryRecord.selectedCountry}" />

Notice that on-focus and on-key-up (i.e. whenever a key is pressed
and released), we call getQuery function to submit a new request
to the server to get updated list. On-blur, we hide the popup list.

Step 6: Create popup div element

Add this code right before the end tag for body:

<div align="left" class="box" id="autocomplete"
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript">

First we define the div element for popup. We then call initPopup javascript
function to size and position the popup element.

Tuesday, September 06, 2005

Tutorial: Using Ajax in a JSF application - I

This tutorial is intended to provide a hands-on experience on implementing an auto-complete Google suggest like TextBox in a JSF application. As mentioned before, we will not create a reusable custom textbox component but rather take a simple approach of using the standard JSF HTML Textbox. This means we will manage the necessary Javascript code in the web application on our own. The application being discussed here would be more useful for a web developer rather than a component developer.

As mentioned earlier, the application will contain a text box to enter a country name. As you type a new character in the text box, it will dynamically get upto 5 matching country names from the servlet and list those names for you to choose from. Once you select a country in the text box and submit the form, it will display a brief description of the selected country. The application itself is pretty simple but it intends to provide the following 2 key concepts:
1. How can we implement a Servlet in a JSF web application to interact with the browser in the client side as well as to interact with the JSF components in the server side to possibly update the server state?
2. How can we implement the Javascript code in the application for Ajax implementation in the client side?

In this part, we will create a simple JSF application without AJAX. In part II, we will extend the same application to implement AJAX.

Step 1: Set up the JSF application framework.

This tutorial is not an introduction to JSF. It is assumed that you already know how to create a JSF application. So the basic framework for this application is already provided. Download it from here and extract it to a folder in your computer. Notice the structure of the extracted files:


Step 2. Add JSF libraries

Add the JSF jar files to ajax/Web-Inf/lib folder.

Step 3: Store the data.

To keep things simple, we will store the country data in a simple txt file separated by tab. In a real world application though, the data would be queried dynamically from the database, web services or some other sources.
As shown above, the data is already provided in ajax/web-inf/classes/demo/ file and is stored in this format:

Luxembourg Western Europe Europe Luxembourg LU
Switzerland Western Europe Europe Bern SZ
France Western Europe Europe Paris FR

Step 4: Read data.

We will read the data from the txt file when the application is initially started and keep it in the memory. We could have read the datasource dynamically for each client request. However, in this simple case, it makes more sense to load the data once at the startup.

Create the file with the following content in ajax/Web-Inf/classes/demo folder:

package demo;

public class CountryBean{
String[] countries;
java.util.HashMap countryDetails = new java.util.HashMap();
public CountryBean(){
//read country data from the text file in=
} catch ( IOex) {
System.out.println("IO Error :" +IOex);

//returns country data
public java.util.HashMap getCountryDetails(){
return countryDetails;

//returns country list
public String[] getCountries(){
return countries;

//read data from the text file
//and store it in countryDetails
private void readData( br)
throws {
int recordNum= Integer.parseInt(br.readLine());
countries = new String[recordNum];
for(int i=0; i<recordNum; i++){
String line=br.readLine();
java.util.StringTokenizer st =
new java.util.StringTokenizer(line, "\t\r");
String name= st.nextToken();
String region= st.nextToken();
String cont = st.nextToken();
String capital = st.nextToken();
String id = st.nextToken();
CountryRecord cr= new CountryRecord(name, region, cont, capital, id);
countryDetails.put(name, cr);
countries[i] = name;

The above class reads the data from the txt file. Notice that in the constructor,
we are calling readData method. In the readData method, we are reading each line from the text file and using the data to create a CountryRecord object to represent each country. The CountryRecord objects are then stored in a HashMap variable named countryDetails. We have also created another String array variable named countries and stored the country names in it.
The two methods getCountryDetails and getCountries simply return countryDetails and countries variables respectively so that they can be accessed from other places in the application.

Step 5: Add the class as a JSF managed bean

Open faces-config.xml from ajax/web-inf folder and add the above class as a managed bean as shown below:


Notice that we have added the bean with application scope because we want to
create a single instance of CountryBean throught the lifecycle of the application so that the database is read just once when the application starts.

Step 6: Create CountryRecord class

The CountryRecord class we used above is a simple class to store each of the country record. Create the file with the following content in ajax/Web-Inf/classes/demo folder:

package demo;
public class CountryRecord {
String name;
String region;
String continent;
String capital;
String id;

public CountryRecord(String name,
String region,
String continent,
String capital,
String id){;
this.continent=continent; = capital;;

public String getName(){
return name;

public String getRegion(){
return region;

public String getContinent(){
return continent;

public String getCapital(){
return capital;

public String getId(){
return id;

Step 7: Create a class to store the selected country information

Next we will create a class to store the state of the user selection. In this case, it is the Selected Country Record. Create the file with the following content in ajax/Web-Inf/classes/demo folder:

package demo;
public class SelectedCountryRecord{
String selectedCountry;
CountryRecord selectedCountryRecord;
java.util.HashMap countryDetails;

public SelectedCountryRecord(){

public String getSelectedCountry(){
return selectedCountry;
public void setSelectedCountry(String selectedCountry){
this.selectedCountry = selectedCountry;

public String getName(){
if(selectedCountryRecord != null)
return selectedCountryRecord.getName();
else return null;
public String getRegion(){
if(selectedCountryRecord != null)
return selectedCountryRecord.getRegion();
else return null;
public String getContinent(){
if(selectedCountryRecord != null)
return selectedCountryRecord.getContinent();
else return null;
public String getCapital(){
if(selectedCountryRecord != null)
return selectedCountryRecord.getCapital();
else return null;
public String getId(){
if(selectedCountryRecord != null) {
if (selectedCountryRecord.getId() != "") {
String id = ""
+ selectedCountryRecord.getId().toLowerCase() + ".html";
return id;
return null;
public boolean isSelected(){
if(selectedCountryRecord != null) return true;
else return false;
public void setSelectedCountryRecord(){
if(selectedCountry != null) {
Object obj = countryDetails.get(selectedCountry);
if((obj != null) &&
(obj instanceof CountryRecord)) {
selectedCountryRecord = (CountryRecord) obj;
else selectedCountryRecord=null;
} else selectedCountryRecord = null;

public void setCountryDetails(){
javax.faces.context.FacesContext context =
javax.faces.application.Application app =
CountryBean cBean = (CountryBean)
countryDetails = cBean.getCountryDetails();

The constructor of this class calls setCountryDetails() method:

public SelectedCountryRecord(){

In the setCountryDetails method, we first get the Application object from FacesContext.
Next, we will get the JSF managed CountryBean that we added above using JSF value binding expression. From the CountryBean, we will get the CountryDetails variable. Remember that this is a hashmap variable which stores the detail information of all countries.

public void setCountryDetails(){
javax.faces.context.FacesContext context =
javax.faces.application.Application app =
CountryBean cBean = (CountryBean)
countryDetails = cBean.getCountryDetails();

The class level variables selectedCountry and selectedCountryRecord store the
user selected country's name and CountryRecord object respectively. Here are the get and set methods for selectedCountry variable:

public String getSelectedCountry(){
return selectedCountry;
public void setSelectedCountry(String selectedCountry){
this.selectedCountry = selectedCountry;

Notice that the set method calls setSelectedCountryRecord() method in addition
to setting the new value. We are calling setSelectedCountryRecord method here because as the user enters a new value for country, we will update the value of selectedCountryRecord too for the new country.

public void setSelectedCountryRecord(){
if(selectedCountry != null) {
Object obj = countryDetails.get(selectedCountry);
if((obj != null) && (obj instanceof CountryRecord)){
selectedCountryRecord = (CountryRecord) obj;
} else selectedCountryRecord=null;
} else selectedCountryRecord = null;

In the above method, we are first getting the new CountryRecord object from
the hashMap by passing the new selectCountry value :

Object obj = countryDetails.get(selectedCountry);

and then we are updating the selectedCountryRecord variable:

selectedCountryRecord = (CountryRecord) obj;

The other methods getName(), getCapital(), getRegion(), getContinent(), getId()simply return the name, capital, region, continent and id respectively from the selectedCountryRecord variable. We will bind these methods with the JSP outputText components to display those values.

Step 8: Add SelectedCountryRecord as a managed bean

Open faces-config.xml from ajax/web-inf folder and add the above class as a
managed bean as shown below:


Notice that this time we have added the bean with the session scope unlike
the previous one. This is because this class contains the data of the selected country for a particular user session. Hence, we need to add it with session scope to create a separate instance to store the individual state of each user session.

Step 9: Compile the above 3 classes

Put the JSF and Servlet libraries in class path and compile the above classes.

Step 10: Create the JSP page

Add this content to ajax/country.jsp file:

<%@ taglib uri="" prefix="h" %>
<%@ taglib uri="" prefix="f" %>
<title>Country Details</title>
value="Integrating AJAX in a simple JSF Application"
<h:outputText value="Enter Country : " />
<h:inputText id="autoText"
value="#{SelectedCountryRecord.selectedCountry}" />
<h:commandButton value="OK" action="success"/>

<h:outputText value="Country Details"
<h:outputText value="Name : "
<h:outputText value="#{}" />
<h:outputText value="Region : "
<h:outputText value="#{SelectedCountryRecord.region}" />
<h:outputText value="Continent : "
<h:outputText value="#{SelectedCountryRecord.continent}" />
<h:outputText value="Capital : "
<h:outputText value="#{}" />
<h:outputText value="More Descriptions : "
<h:outputLink value="#{}">
<h:outputText value="#{}" />


The above jsp page is pretty simple. Notice that we have binded the value of
inputText (to enter the country name) with selectedCountry variable in SelectedCountryRecord bean. The values of outputTexts (to display country information) are binded with the corresponding methods in SelectedCountryRecord bean to return the relevant information for the selected country.

Wednesday, August 24, 2005

Using Ajax in a simple JSF Application - Introduction

I am going to start another tutorial on how to integrate Ajax with JSF soon. This is going to be a very simple JSF application with no GIS component. I hope that this could be of some help to GIS and non-GIS JSF developers alike.
Before I talk about this application, here is a nice article that demonstrates how to create a JSF textbox component with auto-complete feature using Ajax technique:

The above article discusses how to build a custom component that manages the necessary javascript code and can be easily used in a web page. I have, however, used a different approach to create a similar text box. It is simpler in a sense that it doesn't require you to create a custom TextBox component. The downside though is you will have to manage the Javascript code in the jsp page on your own. So if you do not mind writing/using the javascript code yourself, then you might want to give this a try.

The application that I will be discussing will have a text box to enter a country name. As you type a new character in the text box, it will dynamically get upto 5 matching country names from the server and list those names for you to choose from. Once the text box has the selected country name and you submit the form, it will give you a brief description of that country.
To accomplish the Ajax protion of the application, I have used the third strategy discussed in the following article:
If you are a GIS Developer and have gone through my previous discussion on Integrating Ajax with ArcGIS Server, the idea is pretty much the same.

If you would like, you can download this application from here. In order to run this application, simply extract the ajax folder from the zip file, put the JSF jar files in WEB-INF\lib folder and deploy it in a servlet container.

Next time, I will discuss the code behind this application. Stay tuned!!

Tuesday, August 23, 2005

Hidden Input Element

HTML Hidden input element is typically used to transfer hidden data between the client and server. When writing a JSP or ASP application, you might have added a few hidden inputs to your page to persist the data between page reloads. With the evolution of server side technologies like .NET and JSF, the state of a control in the webpage is typically managed in the server side. It is, however, not efficient and sometimes almost impossible to put all data on the server and go back and forth between client and server for every user interaction. Say, for example, in a GIS web application, it would be impossible to post a request to the server to get the map coordinate every time you move the mouse on the map. Hence an efficient web application requires an optimum usage of client side and server side logic which in turn requires transferring the data back and forth between the server and client to make the two sides in synch with each other. The hidden input element can be handy in transferring such data. A typical example of using hidden input elements in a GIS application is passing the updated map extent (minx, miny, maxx, maxy values) between the server and the client.

In my previous blog, I made use of a hidden input element to persist the web page state maintained in the client side. I helped a user with a similar problem using the hidden input element a while ago. This was in .NET. So I thought it would be nice to take a break from Java and talk about it.

The problem was to enable/disable a tool item in the toolbar of the ArcGIS Server MapViewer template on the client side through Javascript without posting back the form immediately. The toolbar is managed by the .NET ADF on the server side. So if you simply change the property on the client side and do not somehow update the change on the server side, you will lose your change the next time your website is loaded. You can, of course, post back the form everytime you enable/disable a toolitem in the client side to synch the server with the client state. However, this means you need to post the form each time you make this change which is not an ideal solution. What would be an ideal solution is to use javascript to enable/disable the toolbar item and when the next time the form is posted, update the state of the toolbar to synch it with the client state.

As mentioned before, we can make use of hidden input control run at the server side to do this. Lets discuss how we can customize the .NET MapViewer template to achieve this functionality:

1. Add a hidden HTML input element to the Default page of the MapViewer template application. Set it to "Run as server Control". Make sure that this is added within the Form element in the HTML source.

2. Add an HTML Button to the page. We will use this button to test our function. Specify onclick="disableToolItem('ZoomOut');" for this button. This button when clicked calls disableToolItem function on the client side and does not post the form.

3. Now lets take a look at disableToolItem function:

function disableToolItem(toolItem){
var f = document.forms[0];
var listValues="";
var Toolbar1 = Toolbars['Toolbar1'];
var items1 = Toolbar1.Items;
disableTool(toolItem, !items1[toolItem].Disabled, true);

listValues += (items1['ZoomIn'].Disabled) ? "0":"1";
listValues += (items1['ZoomOut'].Disabled) ? ":0":":1";
listValues += (items1['Pan'].Disabled) ? ":0":":1";
listValues += (items1['FullExtent'].Disabled) ? ":0":":1";
listValues += (items1['ZoomBack'].Disabled) ? ":0":":1";
listValues += (items1['ZoomNext'].Disabled) ? ":0":":1";
listValues += (items1['Identify'].Disabled) ? ":0":":1";
f.elements['activeToolList'].value = listValues;

Notice that it first toggles the disable property of the given toolItem by calling the custom
function disableTool (see below) and generates a String in
this format: 0:1:1:1:0 where 0 and 1 represent the disabled
and enabled state of the toolitem respectively. It then assigns this value
to the hidden input element and refreshes the toolbar.

4. The disableTool function is given below:

function disableTool(itemName, disable, isTool ){
var Toolbar1 = Toolbars['Toolbar1'];
var items1 = Toolbar1.Items;
items1[itemName].Disabled = disable;
var cellName = 'Toolbar1' + itemName;
var thisCellElement =
thisCellElement.onmousedown == null;
thisCellElement.onmouseover == null;
thisCellElement.onmouseout == null;
} else {
thisCellElement.onmousedown = function () {
if (isTool)
ToolbarMouseDown('Toolbar1', itemName, 'Tool');
ToolbarMouseDown('Toolbar1', itemName, 'Command');

thisCellElement.onmouseover = function () {
ToolbarMouseOver('Toolbar1', itemName);

thisCellElement.onmouseout = function () {
ToolbarMouseOut('Toolbar1', itemName);


This function gets the specified toolbar item and nullifies the
mouse events if disabling. It will activate the mouse events
for toolbar item if enabling.

5. Add the above functions to toolbar_functions.js file in C:\Inetpub\wwwroot\aspnet_client\esri_arcgis_server_webcontrols\9_1\JavaScript folder. (Be sure to keep a back up copy of the original file before you make any change to it.)

6. We need to modify the existing functions as follows:
a) Find ToolbarMouseDown function in toolbar_functions.js file . Inside this function find
this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

b) Inside ToolbarMouseOver function, find this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

c) Inside ToolbarMouseOut function, find this line:

var toolbar = Toolbars[toolbarName];

Add this line after the above line:

if(toolbar.Items[toolbarItemName].Disabled) return;

7. Finally, we need to update the server state when the page is posted back. Modify the Page_Load method of Default page as shown below:

private void Page_Load(object sender, System.EventArgs e)
// Check parameters of MapControl
// If there is no Host or ServerObject defined,
// then there is no point to continuing since there will be no map to display
if ( (Map1.Host == null) (Map1.Host == String.Empty) )
callErrorPage("Host property not defined for the Map control.", null);
if ( (Map1.ServerObject == null)
(Map1.ServerObject == String.Empty)
(Map1.ServerObject == "(none)") )
callErrorPage("ServerObject property not defined for the Map control.", null);
if (!Map1.AutoFirstDraw)
callErrorPage("The property AutoFirstDraw of
the Map WebControl must be set to true
for this application to run.", null);
// check if the server object can be accessed
ESRI.ArcGIS.Server.WebControls.ServerConnection connection =
if ( connection == null )
callErrorPage("Invalid ServerConnection.", null);

// check if the server object is pooled
isPooled = connection.IsServerObjectPooled(Map1.ServerObject,"MapServer");

string activeTools="";
// Is this a PostBack or just started
if ( !Page.IsPostBack )
// Is this a new session?
if ( Session.IsNewSession )
// Save extent history to Session
m_extenthistory = new ArrayList();
Session.Add("extenthistory", m_extenthistory);
m_lastextent = Map1.Extent;

//if new session, generate the string to store
//the enable/disable status of toomitems
//the value will be stored in 1:0:0:1:1 format
//where 1=enable, 0=disable

int toolLength = Toolbar1.ToolbarItems.Count;
for (int i=0;i<toolLength;i++)
string disableOrNot = "1";
Tool tool = Toolbar1.ToolbarItems[i] as Tool;
if(tool.Disabled) disableOrNot = "0";
if(i==0) activeTools = disableOrNot;
else activeTools = activeTools + ":" + disableOrNot;
} else {
Command command1 = Toolbar1.ToolbarItems[i] as Command;
if(command1.Disabled) disableOrNot = "0";
if(i==0) activeTools = disableOrNot;
else activeTools = activeTools + ":" + disableOrNot;
//set the value to the hidden input control
activeToolList.Value = activeTools;
} else {
//if not a new session
//get the values from the input control
//and update the toolitem property

activeTools = activeToolList.Value;
if((activeTools != "") && (activeTools != null))
char[] sep = {':'};
Array aa = activeTools.Split(sep);
for(int i = 0;i<aa.Length;i++)
Tool tool = Toolbar1.ToolbarItems[i] as Tool;
if(tool != null)
if (aa.GetValue(i).ToString()=="0") tool.Disabled = true;
else tool.Disabled=false;
} else {
Command command1 = Toolbar1.ToolbarItems[i] as Command;
if (aa.GetValue(i).ToString()=="0") command1.Disabled = true;
else command1.Disabled=false;
// make sure that the session is still going, if not, display error page
if (Session["extenthistory"]==null)
callErrorPage("Your session has timed out.", null);

sessionId = Session.SessionID;
string scriptString = "\n<script language=javascript>sessionId = '"
+ sessionId + "'; </script>\n";
Page.RegisterStartupScript("SessionIdScript", scriptString);
// get name of session object holding map description
string pagePath = Page.Request.FilePath;
string pageName = "";
int lastSlash = pagePath.LastIndexOf("/");
if (lastSlash>-1) pageName = pagePath.Substring(lastSlash+1);
m_MapDescriptSessName = pageName + Map1.ID + "_md";

Notice above that when the new session is started, we get the toolitem property and
generate the string to assign it to hidden input control. If this is not a new session but a postback request, we parse the value of hidden input control and update the property of the toolitem appropriately. This makes the state of the server toolbar in synch with that on the client side.

Sunday, August 21, 2005

Integrating AJAX with ArcGIS Server - IV

In this final part of Integrating AJAX with ArcGIS Server series, we will discuss how to customize javascript code for the custom magnifier tool. The most challenging part in this section is to integrate our custom tool in the existing toolbar managed by ArcGIS Server ADF. Java ADF manages the active tool through Map Control in the server side. The magnifier tool that we are developing, however, does not submit the request to ADF but to a separate servlet. So we need to develop our own mechanism to integrate this new tool to the existing toolbar. To solve this problem, we will add a JSF hidden input element to store the state (active or not) of the Magnifier tool and customize the javascript code to update the toolbar in client side. Since JSF components are stored in the server side, we will use this hidden input element to maintain the state of the magnifier tool between the postbacks.
With this introduction, lets discuss the code step by step.

1. We will be writing the javascript code in a separate file called ajax.js. So first thing we will do is add the reference to the js file in the mapviewer.jsp page:

<script language="Javascript" src="js/ajax.js">

(We will take a look at this file in a while.)

2. Add the magnifier tool right after the identify tool in the toolbar:

<IMG id="imgMagnifier"
MapPoint('Map0', 'Magnifier');
onmouseout="ButtonOut('imgMagnifier', 'Map0',
'Magnifier', 'images/magnifier.gif',
'images/magnifierD.gif');" />
<jsfh:inputHidden id="btnMagnifierHidden" value="" />

The above code is similar to other tools except these 2 important differences:
a) In onmousedown event, we have called MapPoint function and passed our custom tool id called Magnifier. Since this is not the ADF managed tool but our own tool, we need to manage it through our custom javascript code.
We will discuss the javascript code just in a bit.
b) As mentioned before, we have added a jsf hidden input component to manage the status of the magnifier tool.

3. Save the following images in images folder of the web application as magnifier.gif, magnifierU.gif and magnifierD.gif respectively:

4. Find the identifyResult control tag and add the following code right after it:

<div id="magnifierDiv"
<div id="mainImg">
<IMG id="magnifierDivImg" src="" />
<div id="closeImg"
style="position:absolute;left:180px; top:5px;">
<IMG id="magnifierCloseImg"
onmousedown="closeMagnifier();" />

In the above code, we have added a div element with 2 inner div elements. The first inner div element is to store the magnified image which would be obtained from our custom servlet. The second div element contains a close image which when clicked calls closeMagnifier() function to hide the magnifier div.

5. Toward the end of the jsp file, find the script tag and modify it as shown below:

<script language="JavaScript">
var fid = document.forms[docFormID].id;

var magnifierHidden = document.getElementById(fid+':btnMagnifierHidden');
var mval = magnifierHidden.value;
if(mval =="active"){
document.images["imgMagnifier"].src = "images/magnifierD.gif";
MapPoint('Map0', 'Magnifier');

} else {

The above code checks the value of the hidden input element that we added. If its value is active (which means current active tool is magnifier), we will activate the magnifier tool. Otherwise it will behave in a normal manner.

6. In the HighlighTool function:
a) We need to add this line outside switch statement to unselect the magnifier tool:
document.images["imgMagnifier"].src = "images/magnifier.gif";
b) And this new case statement to select the magnifier tool:

case "Magnifier":
document.images["imgMagnifier"].src = "images/magnifierD.gif";

7. Change the ButtonOut function to handle this new tool:

function ButtonOut(id, control, tool, flatimage, downimage)
var f = document.forms[docFormID];
var m = control + "_mode";
var mode = f.elements[m].value;
var imgsrc = flatimage;
var magVal = document.getElementById(':btnMagnifierHidden').value;
if(magVal =="active"){
if(tool == "Magnifier") imgsrc = downimage;
}else if (mode == tool) {
imgsrc = downimage;
var imgObj = document.getElementById(id);
if(imgObj != null) imgObj.src = imgsrc;

8. In map_functions.js file, find mapSetTool function and add this new variable right before
this function:

var isMagnifier = false;

Add this new code at the top of the mapsetTool function:

var ff = document.forms[docFormID];
var hid = document.getElementById(':btnMagnifierHidden');
if(mode=="Magnifier") {
//set the value of hidden input element
//to active
isMagnifier = true;
//change the cursor to crosshair
else {
isMagnifier = false;
//set empty value for hidden input element

In the above code, we are checking if Magnifier tool is activated. If so, we will set the value
of isMagnifier to true and that of hidden input element to active. If any other tool has been selected, we set the value of isMagnifier to false and that of hidden input element to an empty value.

9. Modify the mapPointClick function as shown below:

function mapPointClick(e) {
if (isLeftButton(e)) {
//call the custom function
sendMagnifierRequest (zleft, ztop);
else {
//post back the form = "wait";
var f = document.forms[docFormID];
postBack(Maps[divIndex].controlname, 'point');
//alert( + "\n" + zleft + "," + ztop);
return false;

Here, we are calling our custom function (that we will be looking soon) instead of posting
back the form if the magnifier tool is active.

10. Now lets take a look at the ajax.js file:

var appName = "AjaxTest";

function getHTTPObject() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
// IE
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;

//XMLHttpRequest object
var req ;

//variables to store x/y location
var ajx, ajy;

//this function sends the request
function sendMagnifierRequest(xx,yy) {
req = getHTTPObject();
ajx = mouseX;
ajy = mouseY;

//for IE, i needed to subtract 2 pixels
//to center the map more accurately
xx -= 2;
yy -= 2;
var url = "/" + appName + "/AgsServlet?x=" + xx + "&y=" + yy;
if (req != null) {"GET", url, true);
req.onreadystatechange = getResponse;

//this function processes the response
function getResponse(){

if (req.readyState == 4) {
if (req.status == 200) {

var result = req.responseText;
//position the div element
var mDiv = document.getElementById('magnifierDiv').style;
mDiv.left = ajx-100; = ajy-100;
//specify the image returned as a src
var magImg = document.getElementById('magnifierDivImg');
magImg.src = result;
//show the div
mDiv.visibility = "visible";


//this function hides the div
function closeMagnifier(){
var mDiv = document.getElementById('magnifierDiv').style;
mDiv.visibility = "hidden";

First we have specified the application name in a variable appName. Make sure to change
this variable with your web application name.

Function getHTTPObject creates and returns a new XMLHttPRequest object. Notice the difference in creating this object between IE and Mozilla.
Function sendMagnifierRequest is responsible for submiting the user click point (x/y values) to our custom servlet. In this function, we first got a new XMLHttpRequest object called req and opened a "GET" connection to our custom Servlet. We have passed the x/y values to the servlet by appending the argument value pair to the url. The following line specifies that getReponse function will be called every time he state of XMLHttpRequest object is changed:
req.onreadystatechange = getResponse;

Remember that one of the key features in Ajax is to send requests asynchronously, i.e. we won't be sitting there and waiting for the response once we submit the request. That is why we have specified the above function that will track the state of the XMLHttpRequest object and processes the response when ready.

In the getResponse function, we will check the state of the XMLHTTPRequest object and if it's value is 4 (i.e. completed) and the HTTP status of the response is 200 (OK), we will then process the response.
Remember from our previous discussion, the custom servlet simply sends back the url of the output image in a simple text format. So we will get this url from responseText property of the req object and set the url as a source to an image in a div element. We will center this DIV element at the click location and finally make it visible.

11. Finally, save the ajax.js file in the js folder of your web application.
Thats it. You are all set to test this new tool. Enjoy!!!