Geo Coding

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.

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:

<managed-context-attribute>

<name>esriAGSSelectionLayer</name>

<attribute-class>test.AGSSelectionLayer</attribute-class>

<description>Selection Layer</description>

</managed-context-attribute>

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.

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

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 AjaxServlet.java 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)

throws java.io.IOException,

ServletException {

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

//get CountryBean object from ServletContext

CountryBean countryBean = (CountryBean)

getServletContext().getAttribute("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");

java.io.PrintWriter out=response.getWriter();

out.print(matches);

out.flush();

}

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException,

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++){

if(countries[i].toUpperCase().

startsWith(key.toUpperCase())){

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

count++;

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) getServletContext().getAttribute("CountryBean");//get list of countriesString[] 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 ServletOpen web.xml file from ajax/WEB-INF folder and add the custom servlet right after Faces Servlet:

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 IEvar isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

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

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:

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/country.data file and is stored in this format:

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 CountryBean.java file with the following content in ajax/Web-Inf/classes/demo folder:

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 CountryRecord.java file with the following content in ajax/Web-Inf/classes/demo folder:

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 SelectedCountryRecord.java file with the following content in ajax/Web-Inf/classes/demo folder:

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.

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

Notice that the set method calls setSelectedCountryRecord() method in additionto 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.

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.

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:https://bpcatalog.dev.java.net/ajax/textfield-jsf/design.html

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:https://bpcatalog.dev.java.net/nonav/ajax/jsf-ajax/frames.htmlIf 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.

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

This function gets the specified toolbar item and nullifies themouse events if disabling. It will activate the mouse eventsfor 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.)

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 = Map1.ServerConnection; if ( connection == null ) callErrorPage("Invalid ServerConnection.", null);

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(); m_extenthistory.Add(Map1.Extent); Session.Add("extenthistory", m_extenthistory); Session.Add("index",0); m_lastextent = Map1.Extent;

Notice above that when the new session is started, we get the toolitem property andgenerate 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"> </script>

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

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

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:

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:

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";break;

In the above code, we are checking if Magnifier tool is activated. If so, we will set the valueof 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.

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!!!