Table of Contents

Introduction
jBox Features
Requirements
Installing the Software
Obtaining jBox
Positioning the Files
Integrating the jBox applet with an existing MapServer application
Add a name attribute to the html form
Add a hidden variable to the form
Add JavaScript functions
Replace output map image definition
A Closer Look
A First Run
Fine-tuning with JavaScript
Turning Box Dragging On and Off
Optional jBox Parameters
Public Methods
JavaScript Functions
Advanced Features
Image Swapping
Distance Measuring
Cursor Coordinate Display
Acknowledgments
Document Changes

Introduction

The jBox Java applet provides interface enhancements to web pages driven by either the MapServer CGI or MapServer/MapScript. This document describes how to add jBox to existing MapServer CGI pages. Users working with PHP MapScript may find the Rosa Java applet more convenient. DM Solutions - Rosa Introduction. Rosa provides functionality similar to jBox but with an interface oriented more toward PHP scripted pages.

jBox runs entirely on the client computer and is therefore independent of the web server. In order for a client browser to run a Java applet, a Java Virtual Machine (VM), must be installed on the client machine. (A Java VM may also be referred to as a "Java Runtime Environment" (JRE)) Microsoft Windows used to ship with Microsoft's VM, however this is no longer the case due to a lawsuit between Sun and Microsoft. Sun's Java VM can be downloaded at: J2SE Downloads

jBox has historically run well on Microsoft Windows / Internet Explorer clients, however newer versions of Windows are not shipping with a Java VM, as noted above. And newer versions of Windows have increasingly restrictive default security settings in Internet Explorer, which may not initially allow Java applets (or any other "Active Content") to run. jBox will generally run under Linux browsers (Netscape, Mozilla, Konqueror 3.1+) assuming a Java VM is installed. jBox has not run on Macintosh clients in the past, however Safari on OSX should support jBox.

jBox works with JPEG and GIF images. jBox also works with PNG images if the client computer has Sun's JRE 1.4.x installed. jBoxPNG supports PNG images on computers with older VMs by way of the sixlegs PNG Library. The jBoxPNG class and source is included with the jBox distribution zip file, and operates identically to jBox. jBoxPNG requires that the sixlegs class tree be installed (see "Installing the Software", below).

jBox Features

The jBox applet adds the following functionality to MapServer/MapScript pages:

Features

Box zooming

Users can "drag a box" over a map using their mouse and then zoom in to the extent defined by the box.

Panning

Users can dynamically pan the map image using their mouse.

Box querying

Users can "drag a box" over a map using their mouse and execute attribute queries for all features that intersect the box.

Map image swapping

Requests for new maps can be loaded directly into the currently displayed page, without reloading the rest of the page.

Distance measuring

A series of distances can be measured by drawing a polyline on the map. Individual segment distances and a cumulative total distance are returned.

Cursor coordinate display

The coordinates of the cursor location can be displayed. (see http://www.kralidis.ca/gis/mapserv/mapplet/howto.htm for details)

Requirements

This document assumes no previous knowledge or experience with Java programming or applet installation. It does, however, assume the following:

Installing the Software

Obtaining jBox

jBox can be obtained at http://MapServer.gis.umn.edu/contributed.html. Click on the jBox link and save the zip file to a local disk.

Unpack the archive file into a new temporary directory. How you go about this will depend on your operating system.

Positioning the Files

Refer to the README file for file descriptions. The .class files are the Java byte code that is required in order to incorporate the applet into your pages. The com/sixlegs/image/png/*.class files are required by the PNG version of jBox.java (jBoxPNG.java).

Alternatively, the .jar file(s) can be used rather than the .class files. Jars are Java ARchives (similar to .tar or .zip files) that contain multiple .class files in a compressed format. Jars have the potential to improve performance by reducing the number of requests that the browser makes for individual .class files. Each .class file requires seperate request, but a .jar file can provide multiple classes in response to a single request. Additionally, a .jar file may be smaller than .class files due to compression. However in some cases (e.g. png.jar) the .jar may supply many more classes than the applet actually requires.

The .java files are the Java source code for the applet. Compiling the source also requires the LiveConnect classes. These files are not required to run jBox or jBoxPNG.java and do not need to be in your web document directory tree.

To make the applet available to your server, you need simply to place the jar file(s) or (class files) somewhere in your web document tree. For example, if your document tree is rooted at

    /usr/local/htdocs
        or
    /Inetpub/wwwroot/
    

then you might make add a couple of subdirectories under htdocs or wwwroot so that you get a path like:

    /usr/local/htdocs/java/jBox
        or
    /Inetpub/wwwroot/java/jBox
    

Then place the jar files in the jBox subdirectory. For JPEG and GIF files, only jBox.jar is required. PNG images require jBoxPNG.jar and also the sixlegs class support png.jar.

Note that the jar files themselves and the directory in which you place them all need to be accessible and readable by the user that your web server runs as (often user "nobody"). Make sure that the file and directory permissions are properly set, and that the web server is properly configured for this.

Integrating the jBox applet with an existing MapServer application

We'll use the MapServer demo as an example. This example outlines only the minimal steps required to integrate jBox into a MapServer page. More sophisticated applications of jBox are discussed later in this document.

The only changes will be to the html template file that defines how your map pages are displayed. For the MapServer demo, this is the file demo.html. There are essentially four steps:

Each of these steps is addressed separately below.

Add a name attribute to the html form

The html form that controls the map interface in demo.html is defined by this line:


      <form method=GET action="[program]">
    

The addition of the name attribute enables us to refer to the form by name in JavaScript functions. So change the line above to look like this:

      <form name="mapserv" method=GET action="[program]">
    

Add a hidden variable to the form

Next, we need to add an html form variable and initialize it with default values. This variable will hold a pair of screen coordinates that define the bounds of a box the user drags with their mouse. Before the form is submitted to MapServer these coordinates will be replaced based on the user's mouse actions. Add the following line to the list of hidden form variables near the bottom of the demo.html page:


      <input type="hidden" name="imgbox" value="-1 -1 -1 -1">
    

Add JavaScript functions

Now we need to add two JavaScript functions to enable communication with the applet. Put these in the <head> section of demo.html, which looks like this by default:

<head><title>MapServer Demo Interface</title></head>

Change that to look like this:

    <head>
      <title>MapServer Demo Interface</title>

      <SCRIPT LANGUAGE="JavaScript">

        function setbox_handler(name, minx, miny, maxx, maxy) {
          document.mapserv.imgbox.value = minx + " " + miny + " " + maxx + " " + maxy;
          document.mapserv.imgxy.value = minx + " " + miny;
          // Additional code can go here prior to the form submit, below.
          // For example, form validation code.
          document.mapserv.submit();
        }

        function seterror_handler(message) { 
          alert(message);
        }

      </SCRIPT>

    </head>
    

Note the use of "mapserv" on the left side of the assignment statements in the setbox_handler function:

      document.mapserv.imgbox.value = ...
      document.mapserv.imgxy.value = ...
    

This is the name attribute that we assigned to the form above. The setbox_handler function is called by jBox and sets the values of the hidden variable, and the seterror_handler function provides a means for the applet to pass error messages out to the user. However, you don't even really need to understand the functions, as you will never call them yourself - that is up to the applet.

Replace output map image definition

Finally, we need to replace the output map image definition with the applet definition. Find the following html snippet in demo.html (it may be strung out all on one line):

        <tr>
          <td colspan="2">
            <INPUT NAME="img" TYPE="image" SRC="[img]" width=600 height=600 border=0>
          </td>

        </tr>
      

This is the definition of an html table cell that contains the output map image generated by MapServer. We need to replace this with the applet definition. Change the above block so that it looks like this instead:

        <tr>
          <td colspan="2">
            <applet 
                  codebase="/java/jBox"
                  archive="jBox.jar"
                  code="jBox.class"
                  width="600"
                  height="600" 
                  name="jBox" 
                  MAYSCRIPT>

              <param name="image" value="http://[host][img]">
            </applet>
          </td>
        </tr>
      

Note: For PNG image support, use


        code="jBoxPNG.class"
        archive="jBoxPNG.jar,png.jar"
       
above.

Let's pick this applet definition apart a bit.

A Closer Look

The <applet> tag

codebase

Specifies the path, relative to the html document root, to the directory containing the needed class file(s). If you put your class files in a directory structure other than /java/jBox, you will need to change the codebase attribute accordingly.

archive

Specifies the name of the Java ARchive (jar) file which contains the Java class files. archive can be omitted if you are placing the *.class files in the codebase directory instead of using a jar file.

code

Specifies the name of the class file that is to be executed.

width

Defines the width and height (in pixels) of the space to be allocated to the applet on the html page. This value should be the same as the width and height of your output map image, which is set to 600x600 in demo.map. Alternately, you can use MapServer's template substitution and define the width and height as:

        width=[mapwidth] height=[mapheight]
                
name

Assigns a name to the applet for use within the html page. This is handy for use in referring to the applet within javaScript code.

MAYSCRIPT

Permits the Java applet to access JavaScript functions (required for the jBox). This attribute prevents an applet from accessing JavaScript on a page without the knowledge of the page author. Attempting to access JavaScript from an applet that does not have the MAYSCRIPT attribute generates an exception. The MAYSCRIPT tag is needed only for Java to access JavaScript; it is not needed for JavaScript to access Java.

Parameters to be passed to the applet are specified in <param> tags embedded between the opening and closing <applet> tags. Here we have defined only one:

Applet parameters

image

Specifies the map image to be loaded into the applet. Must be a fully-qualified URL. The "[host]" and "[img]" specifiers used here are standard MapServer template substitutions, and will be swapped out for the appropriate values when the MapServer parses demo.html.

A First Run

Load the initilization page (demo_init.html) and hit the Initialize button. Select "Zoom In", and you can now define the zoom extent by dragging a box over the map. (You'll need to have the Browse map button on.)

Additionally, if you turn on the Query multiple features button, drag a box, and you'll get back results for all of the features that intersect the bounds of your box.

Fine-tuning with JavaScript

Turning Box Dragging On and Off

It is logical to drag a box across a part of the map to zoom in, or to select objects to query. But what about zooming out (mode=browse, zoomdir=-1), or re-centering the map (mode=browse, zoomdir=0)? In these operations the box doesn't do us much good. Worse yet, dragging a box in either of these situations would cause a zoom-in regardless of the zoomdir setting.

Rather than expecting the user to choose between dragging or clicking dependent on context, you may wish to use the jBox boxon() and boxoff() methods to control when box dragging is enabled and when it is not. As in the prior example, we will assume that the name of the applet was declared as "jBox", then the basic JavaScript syntax for calling the methods is:

      document.jBox.boxoff();
    

In the MapServer demo, you might place the code in an event handler in a form control. For example:

       Zoom Out <input type=radio
                name=zoomdir
                value=-1 
                onClick="document.jBox.boxoff();"
                [zoomdir_-1_check] >
    

In the above example, when the user switches to the "Zoom Out" mode (zoomdir=-1), box dragging is turned off. Obviously you would need to add additional calls in other form controls to turn box dragging on and off as is appropriate to the operation. The following example shows how to turn panning (image dragging) on.


       Pan <input type=radio 
           name=zoomdir
           value=0 
           onClick="document.jBox.dragon();" 
           [zoomdir_0_check] >
    

The state of boxon(), dragon(), etc. is lost each time the page is submitted. Typically you would use some Javascript to reset the state as appropriate to the current mode.

Optional jBox Parameters

So far we have passed one parameter to the jBox, as seen in the following line from demo.html:

    <param name="image" value="http://[host][img]">

  

The "image" parameter must be specified in order for the jBox to function. There are several optional parameters that can be passed as a means of customizing your jBox appearance and functionality. The syntax for specifying these parameters in demo.html is the same as shown above. A tag with the general form

    <param name="somename" value="somevalue">
  

must appear between the opening and closing applet tags. A list of the optional jBox parameters, their purpose and valid values is given below.

Optional parameters

jitter

Specifies how far (in pixels) a user needs to drag their mouse before jBox will believe that they are actually dragging a box. This prevents poorly-executed single-clicks at the mouse from being interpreted as dragged boxes. Values should be integers. Default is five.

color

Specifies the color to use when drawing the mouse-dragged box or the mouse-clicked crosshair cursor. Color values may be specified using either a comma-delimited RGB triplet (for example, value="255,255,255" draws a white box), or the English name for one of thirteen predefined colors (black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white or yellow). Default is red.

thickness

Specifies the thickness (in pixels) of the line to use in drawing the box (does not affect the crosshair cursor or the measure polyline ). Values should be integers. Default is one.

cursorsize

Specifies the radius (in pixels) of the crosshair cursor. Values should be integers. Default is four.

verbose

Enables/disables cursor location reporting. Valid values are "true" or "false". (Mapplet used "on" and "off") Default is "false". Note that in order to use this feature, three additional JavaScript functions must be defined:

mouseenter_handler(name)

Called when mouse enters applet image area.

mouseexit_handler(name)

Called when mouse leaves applet image area.

mousemove_handler(name, x, y)

Called when mouse moves within applet image area and provides cursor coordinates in screen pixels. Typically you put code in this function to convert the pixel coordinates to real-world coordinates and then display the coordinates in the browser's status line.

box

Initial box drawing status. Valid values are "true" or "false". Default is "true". If set to "false", any mouse-button action inside the jBox applet interface will always be represented by the crosshair cursor. The public methods boxon() and boxoff() are used to turn box drawing on and off once the applet has been initialized.

drag

Initial drag status. Valid values are "true" or "false". Default is "false". The public methods dragon() and dragoff() are used to turn box drawing on and off once the applet has been initialized.

busyimage

Specifies an image to display while the jBox is working. Value given must be a fully-qualified URL. Generally only useful when used with the setimage applet method.

Public Methods

boxon()

toggles box drawing on.

boxoff()

toggles box (and line) drawing off.

lineon()

toggles line drawing on, and box drawing off.

lineoff()

synonym for boxoff(), turns both line and box drawing off.

dragon()

turns "Panning" on. When the mouse button is released, screen coordinates for a new map center point are returned.

dragoff()

synonym for boxoff()

setimage(string)

displays the image loaded from the passed url.

setcursor(string)

sets the cursor to one of crosshair, hand or default

version()

returns jBox version number string

JavaScript Functions

jBox uses LiveConnect to communicate between the jBox Java applet and JavaScript functions in the HTML page. When jBox needs to communicate back to the HTML page, it calls a JavaScript function. The following is a list of JavaScript functions that may be called be jBox.

JavaScript Functions

setbox_handler(name, minx, miny, maxx, maxy, redraw)

This function receives the user's mouse coordinates from jBox and does appropriate processing of the coordinates: either copies them into form variables in preparation for a form-submit, or processes them prior to a setimage() call.

seterror_handler(message)

This provides a method for jBox to pass error messages back to the containing page. Below is a typical example:

function seterror_handler(message) { 
	alert(message); 
}
      
reset_handler(name, minx, miny, maxx, maxy)

reset_handler(name, minx, miny, maxx, maxy);

mouseenter_handler(name)

Called when mouse enters applet image area.

mouseexit_handler(name)

Called when mouse leaves applet image area.

mousemove_handler(name, x, y)

jBox uses this function to pass cursor coordinates back to the HTM page. The function will typically convert the pixel coordinates to real-world coordinates and display them in the browser.

measure_handler(name, s, t, n, a)

jBox uses this function to pass distance measurements back to the HTM page. The function will typically convert the pixel distances to real-world coordinates and display them in the browser.

Advanced Features

Image Swapping

The setimage() method allows the jBox applet's image to be replaced without reloading the whole page. The only parameter to setimage() is the URL of the new image to be displayed. In a typical CGI MapServer application this image is created by mapserv in "map" mode. An example JavaScript code snippet follows:

	 
	var url;
	url = ";http://www.somedomain.com/cgi-bin/mapserv";+
		";?mode=map"; +
		";&map="; + mapfile +
		";&mapext="; + extent.join(";+";) +
		";&mapsize="; + width + ";+"; + height +
		";&layers="; + layerlist;
	document.jBox.setimage(url);
		

There are obvious benefits in displaying a new image without reloading the whole page, however there are a couple trade off's to consider:

  • Since MapServer is no longer creating a whole new page from the template file, your JavaScript will have to take care of updating all of the other page elements that may have changed such as the reference map, scale bar, legend, map extent, etc.

  • The browser's location no longer represents the current map. This means that the browser's back button will not take the user back to the previous map. Nor can the location be bookmarked or e-mailed.

Distance Measuring

The distance measuring functionality is designed to mimic the "Measure" and "Ruler" tools found in ArcView and MapInfo, respectively. As of jBox version 1.1, the distance tool also provides area calculation after the user has clicked three or more points. Distance measuring mode is initiated with a call to lineon() and terminated with a call to lineoff() or boxoff() or boxon(). In distance measuring mode jBox draws a polyline connecting the user's mouse clicks and returns a segment distance, total distance, and calculated area to a JavaScript function named "measure_handler()". Double-clicking resets the tool.

The returned distance and area are in screen pixels and must be converted to real world units appropriate for the map projection. Converting these numbers to meaningful values in an un-projected (latitude/longitude) map would require significant calculations, and is not discussed herein. The area and distance are calculated by simple Cartesian geometry formulas, and as such, are appropriate only for relatively small areas.

The JavaScript measure_handler() function must be declared before entering distance measuring mode. The function needs to convert the pixel values returned by jBox into real-world values and display them somewhere in the browser. A simple measure_handler() example is shown below. See http://www2.tetonwyo.org/mapserver for a slightly more sophisticated example.

	function measure_handler(name, s, t, n, a) {
		// c = 1 / 72dpi / 12inches_per_foot * 1.0003state_plane_scale_factor
		var c = 0.0011577546296296;	// constant
		var f = [scale] * c;		// scale factor
		if ((s>0) || (t>0)) {
			defaultStatus = "This segment = " + s*f + ", Total = " + t*f + ", Number of vertices = " + n ;
		}
	}
		

Cursor Coordinate Display

See http://www.kralidis.ca/gis/mapserv/mapplet/howto.htm for details.

Acknowledgments

Most of jBox was written by Steve Lime.

Tom Kralidis <tomkralidis at hotmail.com> contributed the coordinate display functions.

Rich Greenwood <rich@greenwoodmap.com> added the distance measuring / line drawing code.

Ken Boss <kenboss@dilbert.dnr.state.mn.us> wrote the original version of this HOWTO.

Eric Weisbender <Weisbend@wapa.gov> contributed to the development of jBoxPNG.

If there are other contributors that I have not acknowledged here, please contact me at <rich@greenwoodmap.com>.

Document Changes

Revision History
Revision : 1Date: 06/21/2004Author: Kari Geurts
I added the Revision History section to this document.