You are on page 1of 138

Chapter 1: Introduction to ArcGIS Server

At a high level you can think of ArcGIS Server as software that helps you take your geographic
information and make it available to others. This data can be distributed over the Web or
through traditional GIS desktop software like ArcGIS Desktop.

Figure 1: Publish Your Data to World
ArcGIS Server is a software platform for sharing GIS resources internally within your
organization and externally to the world through the web. ArcGIS Server is capable of sharing
many different kinds of resources including maps, globes, address locators, geodatabases, and
tools. Each of these resources can be exposed at your discretion both internally and externally.
Within your organization users can access ArcGIS Server through ArcGIS Desktop, internal web
mapping applications, or mobile applications. Similarly, you can expose your ArcGIS Server
resources to the rest of the world through the web. All these resources are hosted by ArcGIS
Server.
As with any other type of server technology ArcGIS Server provides certain benefits including
the centralized management of your GIS data, multi-user support, and the ability to provide up-
to-date data to your users. ArcGIS Server also comes with an out of the box template that you
can use to create basic web mapping applications along with a number of development tools that
you can use to create custom web mapping applications.
Many clients access the information stored as services in ArcGIS Server. Desktop applications
such as ArcMap, ArcGIS Explorer, and ArcGlobe can all access ArcGIS Server to display data.
Custom web applications built with the JavaScript, Flex, or Silverlight API can also access
services published through ArcGIS Server. Custom applications built using ArcGIS Engine with
ArcObjects can also access ArcGIS Server.
GIS Resources and Services
GIS resources are the maps, geodatabases, address locators, geoprocessing tools, raster datasets,
and other tools you need for storing and using geographic data. Each of these resources is
created in ArcGIS Desktop with ArcMap and/or ArcCatalog. Services are representations of
these resources that ArcGIS Server makes available to other computers through a network.
These services can be accessed through custom web mapping applications or traditional GIS
desktop applications.

Figure 2: GIS Resources and Services
Resources are authored in ArcGIS Desktop using ArcMap or ArcCatalog depending upon the
type of service that will ultimately be created. Lets look at an example. A Map resource can be
published as a Map service that can be dynamically displayed within a web mapping application.
ArcMap would be used to create a map document file or .mxd containing the layers and
symbology that will be part of the service. Once authored this map document resource can be
published as a service.

Figure 3: Creating a Map Document for Publication
GIS resources can be published to ArcGIS Server using either ArcGIS Server Manager or
ArcCatalog.

Figure 4: Publishing a Map Document to ArcGIS Server
When creating services in ArcGIS Server you are going to follow a typical workflow that begins
with the creation of resources in ArcGIS Desktop. These resources are then published as
services in ArcGIS Server and finally, consumed by custom web mapping applications or
traditional desktop applications.

Figure 5: Authoring, Publishing and Consuming Services
The central concept behind ArcGIS Server is that of GIS service. GIS services are resources that
ArcGIS Server makes available to web, desktop, and mobile applications. These client
applications consume the resources provided by ArcGIS Server. There are many types of GIS
services including maps, geoprocessing tasks, locators, globes, images, and more
ArcGIS Server can host a number of different service types including maps, geocoding, images,
geoprocessing, and others. Each of these services can be created on the server and made
available to client applications. The server does all the work of hosting data, creating and
hosting services, performing the GIS work, and sending results back to the client. In many cases
these services will be provided through a customized web application, but they can also be
consumed by ArcGIS Desktop applications as well as mobile devices. Each of these resources is
created and administered through ArcGIS Desktop and then hosted by ArcGIS Server.
The Services Directory
As a developer you will want to become intimately familiar with the ArcGIS Services directory.
This resource contains invaluable information about the services that are available through an
ArcGIS Server instance. The services directory contains the names of all services published by
the instance, metadata about each service including a description, the layers associated with a
service, spatial extents, attribute fields, definition expressions, min and max scales, and more.
You will use this services directory frequently when developing custom applications with
ArcGIS Server.
Each ArcGIS Server instance contains a Services directory that can be accessed through the web
and contains information about the services made available by a particular ArcGIS Server
instance. This directory contains a list of the available services and the properties of those
services. To access this directory you need to know the URL of the service instance. Normally
the Services directory is found in the arcgis/rest directory as you can see from the example
below.
http://sampleserver1.arcgisonline.com/ArcGIS/rest/services
ArcGIS Server Components
There are several components of the ArcGIS Server system. The primary component is ArcGIS
Server which consists of a Server Object Manager or SOM and one or more Server Object
Containers or SOCs. These two components play specific roles. The SOM and SOCs can be
installed on the same machine or distributed to multiple machines. ArcGIS Server also consists
of services, applications, and KML network links that have been published to the server. In
addition, a Manager application is responsible for creating and organizing services and basic
applications. Other components of the system include a web server for hosting applications and
service created by ArcGIS Server. Finally, web, desktop, and mobile applications consume the
services hosted on ArcGIS Server.
Architecturally, ArcGIS Server is comprised of two parts: Server Object Manager (SOM) and
one or more Server Object Containers (SOCs). A single SOM per instance of ArcGIS Server
manages the services running on the server. It is responsible for connecting service requests
from clients to a particular service which is contained within a SOC. SOCs are responsible for
filling service requests as they come in and there can be multiple SOCs per ArcGIS Server
instance. In simple installations, the SOM and SOCs can be co-located on the same server.
However, in systems that expect heavy use it is common to install the SOM and SOCs on
different machines to distribute the work load. In addition, SOCs can be installed on multiple
machines as well to further distribute the work load.

Figure 6: The ArcGIS Server Components
As I mentioned, ArcGIS Server is composed of a SOM and one or more SOCs. The SOM
manages the set of services that are distributed across the SOCs. When an application makes a
direct connection to a GIS server over a LAN or WAN, it first makes a connection to the SOM,
which then finds an available service instance to assign to the client for the lifetime of the
transaction.
SOCs host the services that are managed by the SOM. All services run on all SOCs, so it's
important that all SOCs have access to the resources and data necessary to run each service. You
can set the capacity value of a SOC to limit the number of running service instances it can host at
one time.
Each SOC machine is capable of hosting multiple SOC processes. Each SOC process can have
one or more service instances of the same service configuration running within it. The SOM
coordinates starting and stopping SOC processes by using the ArcSOCMon process, which
maintains the state of the container processes should the SOM be disconnected or fail
unexpectedly. The objects hosted within the SOC processes are ArcObjects components that are
installed on the SOC machine as part of the installation of ArcGIS Server.
The SOM, ArcSOCMon, and SOC are processes that run on a machine. A single machine can act
as both a SOM and a SOC in an ArcGIS Server configuration. All machines in an ArcGIS Server
configuration have an ArcSOCMon process. If desired, the Web server and the Web Application
Developer Framework (ADF) can coexist with the SOM and the SOC, allowing a deployment of
ArcGIS Server on just one machine. This type of configuration is useful for development and
testing purposes, as well as small deployments.

Figure 7: The ArcGIS Server SOM and SOC
The Geodatabase
When it comes to data storage there are several things that you will need to consider. ArcGIS
Server will need to have access to the data used in the servies as well as permissions to view
and/or edit the data so you must consider how and where this data will be stored. Generally the
choice should come down to using either ArcSDE or a file geodatabase. In most cases ArcSDE
is the best choice. It works with relational database management systems such as SQL Server or
Oracle which will allow you to store your spatial data alongside other non-spatial data. Using a
RDMS does require the skills of a database administrator or DBA to support the geodatabase.
ArcSDE provides high availability, backup and recovery, concurrency, scalability, versioning,
geodatabase replication and historical archiving which are not available with file geodatabases.
There are some cases when you will not be able to use ArcSDE and file geodatabases can
provide a good alternative. If your datasets are relatively static or you do not have a RDBMS or
DBA then a file geodatabase would make sense. File geodatabases do provide very high
performance. However, you will not be able to use versioning or database replication.
There are other considerations when using a file geodatabase. It is best practice to place an
identical copy of a file geodatabase on each SOC machine in cases where you have a distributed
deployment with multiple SOC machines. You should not attempt to access the same file
geodatabase over the network. This will minimize network communication traffic. File
geodatabases work well in read-only applications, but not so well in editing applications since
editing acquires a lock on the data during editing. This affects the ability of other application
instances to access the data. File geodatabases also work well for map caching scenarios. By
placing an identical file geodatabase on each machine working on the cache, you can eliminate
the many calls to an ArcSDE database that would need to occur across the network. This can
lighten the load on your database and speed up the caching.
ArcSDE, which is bundled with ArcGIS Server, is used in the implementation of Enterprise level
geodatabases. ArcSDE serves as a gateway between ESRI clients and RDBMS such as Oracle,
SQL Server, PostgreSQL, DB2, and Informix. The primary job of ArcSDE is to handle the
storage of geographic data within these RDBMS which have traditionally not had integrated
spatial data types. That has changed over the years with the Oracle Spatial product and
Microsoft SQL Servers latest release which inherently stores geographic data. However,
ArcSDE still serves an important role in managing geographic data in these databases as well as
efficiently querying the data and retrieving the results

Figure 8: ArcGIS Server/ArcSDE Architecture
ArcGIS Server Deployment Options
ArcGIS Server provides a scalable architecture with numerous deployment options. How you
choose to distribute the components of ArcGIS Server depends on how you expect the system to
be used. If you have a small deployment or are in a testing and development phase then
installing all components on the same machine may well make the most sense. Larger
deployments with a large community of users and heavy system access will need to consider
other options where the components are spread among multiple machines.
A single machine deployment will call for the installation of all ArcGIS Server components on
the same machine. This includes the SOM, SOC, Web ADF, web server, ArcSDE and the
RDBMS. This configuration works well for small deployments or development and testing
environments where the number of service requests is small.
A multi-machine deployment architecture makes sense for larger scale deployments that will be
accessed by multiple users simultaneously in either a web or internal environment. In this
architecture the SOM, web server, and Web ADF are typically on the same machine. The SOM
uses a relatively small amount of memory so there is little problem with having it share a
machine with the web server. The SOC(s) are distributed across one or more machines
depending upon the load. This component of the architecture tends to require the most planning
since you need to get an accurate estimate of how many users will be simultaneously using the
system. Finally, the data tier, composed of ArcSDE and the RDBMS would run on a separate
machine.
Hopefully this chapter has given you a good overview of ArcGIS Server and how it can be used
to serve resources. We will now turn our attention to the focus of this book which is the creation
of custom web mapping applications using the ArcGIS Server API for JavaScript in conjunction
with services made available through ArcGIS Server.
You have a number of options when it comes to developing custom web applications with
ArcGIS Server including the JavaScript, Flex, and Silverlight APIs along with the .NET and Java
ADF. In this book well focus specifically on the JavaScript API. Each of the APIs provides the
same basic functionality with a few differences, but in my opinion the JavaScript API is
preferable for a number of reasons. Both the Flex and Silverlight APIs require the installation of
a plugin for any web browser that will use an application built with either of these APIs. This
isnt acceptable in many organizations, and makes mobile application development downright
impossible unless you are using JavaScript. JavaScript is also a fairly easy language to learn,
mixes well with HTML, is tightly integrated with the new HTML5 specification, and has many
frameworks that can be used to make your development efforts easier. In this book we will
specifically use the Dojo Javascript framework for our development efforts. As youll see the
ArcGIS Server API for JavaScript and the Dojo framework are very tightly integrated.
Note: For a more in-depth treatment of the ArcGIS Server API for JavaScript please refer
to our Building Custom ArcGIS Server Applications with JavaScript. This course is
offered as both a traditional instructor led course and an instructor guided online course.
For more information on this course please visit our website at geospatialtraining.com.

Chapter 20: Basic Application Design with Dojo and ArcGIS Templates
One of the most difficult tasks for many web developers building GIS applications is designing
and creating the user interface. The ArcGIS Server API for JavaScript and Dojo greatly
simplifies this task. Dojos layout dijits provide a simple, efficient way to create application
layouts and ESRI has provided a number of sample application layouts and templates that you
can use to get up and running quickly.
Dojo BorderContainer
Since the AGIS API for JavaScript is built directly on top of Dojo you automatically have access
to the user interface libraries including layout dijits such as BorderContainer. BorderContainer
serves primarily as a container for other child containers and can be one of two design types:
headline or sidebar. You define the design type using the design attribute. In either case,
whether you define a design type of headline or sidebar is split into as many as 5 different
regions: top, bottom, right, left, and center. Each region is normally filled by a Dojo layout
element.
In the first code example we are defining the design to be of type headline which results in the
general configuration that you see below with the top and bottom regions stretching across
the entire width of the screen space. In this case you only need to set the height property for
the top and bottom regions.

In the second code example we define the design as sidebar. With the sidebar design the left
and right regions expand to take up 100% of the height of the window, sacrificing the area
available to the top and bottom regions. In this case you only need to define the width style
property since the height will always be 100%.

In either case the center region will conform to fit the amount of space available based on the
sizing of the other regions.
Below you will see an illustration of the differences between the two design types.

Child Elements of BorderContainer
Each region of a BorderContainer (top, bottom, left, right, center) can be filled by a Dojo layout
element. These elements are AccordionContainer, ContentPane, SplitContainer, StackContainer,
and TabContainer. You can also create nested BorderContainers to further divide the available
layout space.
Child elements are placed inside a region through the use of the region attribute as seen in the
code example below. Notice in the yellow highlighted section that the region attribute is set to
left. This will create a ContentPane in the left region. A ContentPane is a very basic layout
element and is used as a container for other widgets. In this case it is going to hold a
TabContainer (green highlighted code) which contains additional ContentPane objects.

AccordionContainer
AccordionContainers hold a set of panes whose titles are visible, but only one panes content is
visible at a time. As the user clicks a title, the pane contents become visible. These are excellent
user interface containers that can hold a lot of information in a small area.

ESRI Sample Layouts
ESRI has provided a number of sample layouts that you can use to get started in the layout of
your application. Go to the ArcGIS API for JavaScript Samples and click Layouts on the left
hand side to see the available layouts. If you see one you like you can easily copy and paste the
code into your application files to get started. Spend some time getting to know the various
options provided by BorderContainer and its child layout elements.

Using ArcGIS.com Templates
You can also use ArcGIS.com templates as a starting point for your applications. There are 3
basic steps you need to follow in this case. You first need to create a new map using the
ArcGIS.com viewer and select a Web application template. Next, download the selected
template and personalize the layout. Finally, add any widgets you need to customize your
application.
Using ArcGIS.com or ArcGIS.com viewer you can create, edit, and share maps. The first step to
using an ArcGIS.com template is to go to ArcGIS.com, login, and then create a new map. Once
a map has been built with the viewer you can then embed this map into an existing site or use
one of the provided templates. These templates are a new feature that allow you to make a basic
Web application out of your map without writing any code.
To obtain a template from ArcGIS.com youll first need to share the map that youve created and
then click Make a Web Application . This will display a gallery of templates that you can
preview and download. Find one you like and then click the download link and follow the
instructions to install and configure the template.
Each template comes with a readme file that provides instructions on how to perform common
customizations like adding a company logo and modifying the layout text. A critical step
explained in the readme file is how to put your map ID in the template, so that your Web
application "knows" which map from ArcGIS.com that it needs to display.
The downloaded template includes all the images and style rules used to define the application
look and feel. The style rules are included in a CSS file and define how elements in the Web
page like links, borders, headers etc. appear.
Once youve downloaded and unzipped the template you will find the directory structure as seen
in the figure below. There will be folders for css, documentation, images, and javascript along
with the stand-alone files index.html and readme.html. To add widgets to your application youll
need to make changes to index.html which is highlighted here as well as layout.js which can be
found in the javascript folder.

The final step is to add any optional custom widgets to your application.



Chapter 2: Introduction to Dojo for ArcGIS Server Development
In this chapter well cover a number of introductory topics related to Dojo and ArcGIS Server.
The ArcGIS Server API for JavaScript is built on top of the Dojo framework so there is a tight
integration between the two.
Dojo core is the foundation for all three projects and handles browser normalization, fixes
browser incompatibilities, allows DOM querying, remote scripting, drag and drop, data store
API, localization and internationalization, Firebug integration, cookie handling, accessibility, and
much more.
Dojo takes care of a lot of the lower level functions such as handling core functionality and
browser differences. This is important for application developers because it hides a lot of the
tedious work involved in testing for browser differences and allows you to focus on developing
your GIS applications.
Dijit includes the Dojo framework along with roughly 40 HTML user interface widgets
including buttons, text boxes, color pickers, sliders, and many others. Tundra is the default CSS
theme for Dijit and is designed to blend into existing color palettes and design. Several additional
themes can be used to fit your user interface design needs.
DojoX are Dojo extensions and includes projects such as the grid widget, a graphics library,
charting, image handling and more. These often include some very sophisticated projects which
are not necessarily as stable as what youll find in Dojo or Dijit.

Figure 9: The Dojo Projects
Everything in Dojo is built around Dojo Base which is the foundation for everything else in
Dojo. Base provides language and AJAX utilities, a packaging system that allows you to pull in
Dojo resources on-the-fly, and many other lower level functions. Core builds on Base by
offering additional facilities for parsing widgets, advanced animation effects, drag-and-drop
facilities, internationalization, back-button handling, managing cookies, and more. Dijit is built
directly on Core and provides an assortment of widgets that you can use to build your user
interface. These widgets are very simple to add to a web page. DojoX is a collection of
subprojects that are extensions or experimental projects. The grid is perhaps the most commonly
used DojoX extension. Finally, Util is a collection of Dojo utilities that includes a JavaScript
unit-testing framework and build tools for creating custom versions of Dojo for production
settings.

Figure 10: Dojo Architecture
Dijit is one of the primary reasons ESRI chose Dojo. Dijits is a widget system layered on top of
Dojo. Using Dijits, you can build amazing Web 2.0 GUI's using very little, or no, JavaScript.
You can use Dijit in one of two ways: declaratively by using special attributes inside of regular
HTML tags, and programmatically through JavaScript. Dijits comes bundled with its own
themes (tundra, soria, and nihilo) which brings a common design and color scheme to all the
widgets. You can override the theme by container or by element to add nuance and flair.
Integrating ArcGIS Server with Dojo
In this section you will learn about the integration of ArcGIS Server with Dojo. First, well
examine the ArcGIS Server architecture as it relates to Dojo. As you may recall, the ArcGIS
Server JavaScript API is built directly on top of Dojo so there is a very tight integration between
the two. For each ArcGIS Server JavaScript application that you build, certain boilerplate code
must be included. This includes creating references to the API and style sheets as well as the use
of dojo.require to import the various resources that you will need to use in your application.
Finally, initialization scripts are, as their names implies, JavaScript functions that perform
various setup actions for your application on startup.

Figure 11: Dojo + ArcGIS Server API for JavaScript
With every ArcGIS Server JavaScript API application that you write a number of lines of
boilerplate code MUST be included. There are no exceptions here. Without this boilerplate
code nothing else can be accomplished. Essentially there are four steps that you'll need to follow
in terms of the boilerplate code that is included. In this chapter Im going to introduce these
steps at a high level. In the next chapter well discuss the programmatic implementation of these
steps, but for now I just want you to understand them at a high level.
First, in the <head> section of your HTML page you will need to include references to the
ArcGIS Server API for JavaScript as well as the Dojo style sheet you intend to use. Remember
that referencing the ArcGIS Server API also includes access to Dojo. This reference must be
placed in the <head> section of your web page, and also needs to include a version number. This
version number refers to the version of the ArcGIS Server API for JavaScript you want to use.
Currently this is version 2.6.
Next, in the <body> or a <div> tag in your web page you need to include a reference to the style
sheet that was included in the first step. Dojo includes style sheets for the tundra, soria,
nihilo, and claro themes or you can choose to build your own custom theme. These style
sheets are primarily used to control the look and feel of the user input widgets supplied through
Dijits.
You then need to add dojo.require statements to import the various ArcGIS Server and Dojo
resources that your application will use. Dojo.require acts in a similar way to include or
import statements found in other languages in that it is used to import resources that will be
used within the application. Instead of loading all resources at one time, which would hurt the
performance of an application, you simply include the resources you need for your application.
In our case, we use dojo.require to import both ArcGIS Server and Dojo resources. In the case
of Dojo resources youll often include user interface components found in Dijit or DojoX.
Furthermore, you will also need to import the ArcGIS Server resources you need in your
application. How do you know which resources to import? Well examine some of the
commonly used ArcGIS Server resources as we move through the chapters. Assuming that you
will be creating maps in your application you will always include esri.map and from there
youll also need to include other resources as necessary. Dojo.require statements should be
placed inside the <head> section of your web page.
After including the boilerplate code that references the ArcGIS Server JavaScript and Dojo
APIs along with the style sheet information and resources have been imported you will need to
create an initialization script that will run immediately after all web page components have
loaded. This initialization script is simply a JavaScript function that is used for initial setup
operations including variable initialization, creation and centering of your map, loading of
datasets, and other common setup tasks. You can give your initialization function any name
youd like, but typical names include initialize and init. The dojo.addOnLoad function is
passed the name of your JavaScript function and handles the calling of this function only after all
web page components have loaded. It is necessary to wait until all web page components have
loaded before running this function because there are times when your initialization function will
need access to particular web components and you must ensure that these components have been
loaded on the page. Otherwise, errors in your application will occur.
Note: For a more in-depth treatment of the ArcGIS Server API for JavaScript please refer
to our Building Custom ArcGIS Server Applications with JavaScript. This course is
offered as both a traditional instructor led course and an instructor guided online course.
For more information on this course please visit our website at geospatialtraining.com
Chapter 3: Introduction to HTML, JavaScript, and CSS
There are certain fundamental concepts that you need to understand before you can get started
with developing GIS applications with the ArcGIS Server API for JavaScript. For those of you
already familiar with HTML, JavaScript, and CSS you may wish to skip ahead to the next
chapter. However, if youre new to any of these concepts read on. We are only going to cover
these topics at a very basic level. Just enough to get you started. For a more advanced treatment
of any of these subjects there are many learning resources available including books and online
tutorials. Please consult Appendix I for a more comprehensive list of these resources.
Basic HTML Page
Before we dive into the details of creating a map and adding layers of information you need to
understand the context of where the code will be placed when youre developing applications
with the API for JavaScript. The code you write will be placed inside an HTML page or
JavaScript file. HTML files typically have a file extension of .html or .htm and JavaScript files
have an extension of.js. Once you have created a basic HTML page you can then go through the
necessary steps to create a basic map with the ArcGIS Server API for JavaScript.
The core of a web page is an HTML file. Coding this basic file is quite important as it forms the
basis for the rest of your application. Mistakes that you make in the basic HTML coding can
result in problems down the line when your JavaScript code attempts to access these tags.
Below is a code example for a very simple HTML page. This example is about as simple as an
HTML page can get. It contains only the primary HTML tags <DOCTYPE>, <html>, <head>,
<title>, and <body>.

There are a number of flavors of HTML currently in used. The most common are HTML 4.01
(seen in the code example above) and XHTML 1.0. In addition, XHTML 1.1 and the new
HTML 5 are also in use. The new HTML 5 is getting a lot of press and youll likely see this
implementation being used more and more.
DOCTYPE
The first line of your HTML page will contain the DOCTYPE. This is used to tell the browser
how the HTML should be interpreted. The two most common DOCTYPEs are HTML 4.01
Strict and XHTML 1.0 Strict:
HTML 4.01 Strict

XHTML 1.0 Strict

Primary Tags
At a minimum all your web pages will need to contain the <html>, <head>, and <body> tags.
The <html> tag defines the whole HTML document. All other tags must be placed inside this
tag. Tags that define how the web page will appear in the browser are placed inside the <body>
tag. For instance, your mapping applications will contain a <div> tag inside the <body> tag that
is used as a container for displaying the map.
Loading this HTML page in a browser would produce the content you see in the figure below.
Most of the ArcGIS Server API for JavaScript code that you write will be placed between the
<head> tags and within a <script> tag or inside a separate JavaScript file. As you gain
experience you will likely begin placing your JavaScript code inside one or more JavaScript files
and then referencing them from the <head> section. Well explore this topic later. For now just
concentrate on placing your code inside the <head> tags.

Figure 12: Hello World
Validating HTML Code
Ive mentioned that it is very important that your HTML tags be coded correctly. This is all well
and good you say, but how do I know my HTML has been coded correctly? Well, there are a
number of HTML code validators that you can use to check your HTML. The W3C HTML
validator (http://validator.w3.org/) shown in the figure below can be used to validate HTML
code by URI, file upload, or direct input.

Figure 13: W3C Validator
Assuming that your HTML code successfully validates you will get a nice screen with a green
message indicating a successful validation.


Figure 14: Successful Validation
On the other hand it will identify any problems with a red error message. Errors are described in
detail which makes it easier to correct problems. Often a single error can lead to many other
errors so it is not uncommon to see a long list of error items. Dont panic if this is the case.
Fixing one error often resolves many others.

Figure 15: Validation Error
JavaScript Fundamentals
As the name implies, the ArcGIS Server API for JavaScript, requires that you use the JavaScript
language when developing your application. There are some fundamental JavaScript
programming concepts that you will need to know before starting to build your application.
JavaScript is a lightweight scripting language that is embedded in all modern web browsers.
Although JavaScript can certainly exist outside the web browser environment in other
applications it is most commonly known for its integration with web applications. All modern
web browsers including Internet Explorer, Firefox, and Chrome have JavaScript embedded. The
use of JavaScript in web applications gives the ability to create dynamic applications that do not
require round trips to the server to fetch data, and thus the applications are more responsive and
natural to the user. However, JavaScript does have the capability of submitting requests to the
server, and is a core technology in the AJAX stack. One common misconception regarding
JavaScript is that it is actually a simplified version of Java. The two languages are actually
unrelated with the exception of the name.

Variables
Variables are a fundamental concept that you need to understand when working with any
programming language. Variables are simply names that we use to associate with some type of
data value. At a lower level, these variables are areas of space carved out in a computers
memory that store data.
You can think of a variable as a box that has a name and which contains some sort of data.
When we initially create the variable it is empty until data is assigned. Basically, variables give
us the ability to store and manipulate data. In the figure below we create a variable called ssn.
Initially this variable is empty but is then assigned a value of 467-63-6732. The data value
assigned to a variable can be of various types including numbers, strings, booleans, objects, and
arrays.

Figure 16: Creating a Variable
In JavaScript, variables are declared with the var keyword. In general, the names that you
assign to your variables are completely up to you. However, there are certain rules that you need
to follow when creating a variable. Variables can contain both text and numbers but should
never start with a number. Always start your variable name with a letter or underscore. In
addition, spaces are not allowed within variable names nor are special characters such as percent
signs and ampersands. Other than that you are free to create variable names as you wish but you
should try to assign variable names that describe the data that the variable will be assigned. It is
also perfectly legal to declare multiple variables with the same var keyword, and you can also
combine variable declaration with data assignment as seen in the examples seen below.
var i = 10;
var j = 20;
var k = 30;
JavaScript is Case-Sensitive
One very important point that I need to make is that JavaScript is a case-sensitive language and
you need to be very careful about this because it can introduce some difficult to track down bugs
in your code. All variables, keywords, functions, and identifiers must be typed with a consistent
capitalization of letters. This gets even more confusing when you consider that HTML is not
case sensitive. This tends to be a stumbling block for new JavaScript developers. Below I have
created three variables, all with the same spelling, but because they do not follow the same
capitalization pattern you end up with three different variables.
var myName = Eric;
var myname = Eric;
var MyName = Eric;
Variable Data Types
JavaScript supports various types of data that can be assigned to your variables. Unlike other
strongly typed languages like .NET or C++, JavaScript is a loosely typed language. What this
means is that you dont have to specify the type of data that will occupy your variable. The
JavaScript interpreter does this for you on the fly. You can assign strings of text, numbers,
boolean true/false values, arrays, or objects to your variables.
Numbers and strings are pretty straight-forward for the most part. Strings are simply text
enclosed by either a single or double quote. For instance:
var baseMapLayer = Terrain;
var operationalLayer = Parcels;
Numbers are not enclosed inside quote marks and can be integers or floating point numbers.
var currentMonth = 12;
var layered = 3;
var speed = 34.35;
One thing I would point out to new programmers is that numeric values can be assigned to string
variables through the user of single or double quotes that enclose the value. This can be
confusing at times for some new programmers. For instance, a value of 3.14 without single or
double-quotes is a numeric data type while a value of 3.14 with single or double quotes is
assigned a string data type.
Other data types include booleans which are simply true or false values, and arrays which are a
collection of data values. An array basically serves as a container for multiple values. For
instance, you could store a list of geographic data layer names within an array and access them
individually as necessary.

var male = false;
var female = true;
Objects deserve special consideration and well examine them in a lot greater detail as we
advance through the book. Basically, objects are named pieces of data that have both properties
and methods. Objects that are part of the ArcGIS Server API for JavaScript are stored in object
variables.
Functions
Now lets cover the very important topic of functions. Functions are simply named blocks of
code that execute when called. The vast majority of the code that you write in this course and in
your development efforts will occur within functions that you define.
Best practice calls for you to split your code into functions that perform small, discrete units of
operation. These blocks of code are normally defined in the <head> section of a web page inside
a <script> tag, but can also be defined in the <body> section. However, in most cases you will
want your functions defined within the <head> section so that you can ensure that they are
available once the page has loaded.
To create a function you need to use the function keyword follow by a function name that you
define and any variables necessary for the execution of the function passed in as variables. In the
event that you need your function to return a value to the calling code you will need to use the
return keyword in conjunction with the data you want passed back.

Objects
Now that weve gone through some basic JavaScript concepts well tackle the most important
concept in this section. In order to effectively program mapping applications with the ArcGIS
Server API for JavaScript you need to have a good fundamental understanding of objects so this
is a critical concept that you need to grasp to understand how to develop web mapping
applications.
The ArcGIS Server API for JavaScript makes extensive use of objects. Well cover the details of
both programming libraries, but for now well hit the high level concepts. Objects are complex
structures capable of aggregating multiple data values and actions into a single structure. This
differs greatly from our primitive data types like numbers, strings, and booleans which can hold
only a single value. Objects are much more complex structures.
Objects are composed of both data and actions. Data, in the form of properties, contains
information about an object. For example, with a Map object found in the ArcGIS Server
JavaScript API there are a number of properties including the map extent, graphics associated
with a map, the height and width of the map, layer ids associated with the map and more. These
properties contain information about the object.
Objects also have actions which we typically think of as methods, but we can also group
constructors and events into this category. Methods are actions that a map can perform such as
adding a layer, setting the map extent, or getting the map scale.
<OMD figure here>
Constructors are special purpose functions that are used to create new instances of an object.
With some objects it is also possible to pass parameters in to the constructor to give more control
over the object that is created. Events are actions that take place on the object and are triggered
by the end user or the application. This would include events such as a map click, mouse move,
or a layer being added to the map.
Properties and methods are accessed via dot notation wherein the object instance name is
separated from the property or method by a dot. For instance, to access the current map extent
you would enter map.extent in your code. The same is the case with methods except that
methods have parentheses. When data is passed into a method via parameters they are placed
inside the parentheses.

Basic CSS Principles
CSS or Cascading Style Sheets is a language used to describe how HTML elements should be
displayed on a web page. For instance, CSS is often used to define common styling elements for
a page or set of pages such as the font, background color, font size, link colors, and many other
things related to the visual design of a web page.

CSS Syntax
A CSS rule has two main parts; a selector and one or more declarations. The selector is typically
the element that you want to style. In the example below, the selector is p. A p element in
HTML represents a paragraph. The second part of a CSS rule is one or more declarations each
of which consists of a property and a value. The property represents the style attribute that you
want to change. In our example, we are setting the color property to red. In effect what we
have done with this CSS rule is to define that all text within our paragraph should be red.
p {color:red}

Figure 17: CSS Syntax
You can include more than one declaration in a CSS rule as you see in the example below. A
declaration is always surrounded by curly brackets and each declaration ends with a semi-colon.
In addition, a colon should be placed between the property and the value. In this particular
example two declarations have been made. One for the color of the paragraph and another for
the text alignment of the paragraph. Notice that the declarations are separated by a semi-colon.
p {color:red;text-align:center}
CSS comments are used to explain your code. You should get into the habit of always
commenting your CSS code just as you would with any other programming language.
Comments are always ignored by the browser. On this slide you see an example of how a
comment is defined in CSS. Comments begin with a slash followed by an asterisk and end with
an asterisk followed by a slash. Everything in between is assumed to be a comment and is
ignored.

In addition to specifying selectors for specific HTML elements you can also use the id selector
to define styles for any HTML elements with an id value that matches the id selector. An id
selector is defined in CSS through the use of the #pound sign followed by an id value.
For example, in the code example below you see three id selectors: rightPane, leftPane, and
map. In ArcGIS Server API for JavaScript applications you almost always have a map. When
you define a <div> tag that will serve as the container for the map you define an id and assign
it a value which is often map. In this case we are using CSS to define several styles for our
map including a margin of 5 pixels along with a solid styled border of a specific color and a
border radius.


Figure 18: Map Border Styling
Unlike id selectors which are used to assign styles to a single element, class selectors are used
to specify styles for a group of elements all of which have the same HTML class attribute. A
class selector is defined with a period followed by the class name. You may also specify that
only specific HTML elements with a particular class should be affected by the style. Examples
of both are shown in the code example below.


There are three ways to insert CSS into your application: external style sheets, internal style
sheets, and inline.
External Style Sheet
An external style sheet is simply a text file containing CSS rules and saved with a file extension
of .css. This file is then linked into all web pages that want to implement the styles defined
within the external style sheet through the use of the HTML <link> tag. This is a commonly
used method for splitting out the styling from the main web page and gives you the ability to
change the look of an entire website through the use of a single external style sheet.
Internal Style Sheet
An internal style sheet moves all the CSS rules into a specific web page. Only HTML elements
within that particular page have access to the rules. All CSS rules are defined inside the <head>
tag and enclosed inside a <style> tag as seen in the code example below.

Inline Styling
The final method of defining CSS rules for your HTML elements is through the use of inline
styles. This method is not recommended because it mixes style with presentation and is difficult
to maintain. It is an option though in some cases where you only need to define a very limited
set of CSS rules. To use inline styles simply place the style attribute inside the relevant HTML
tag.

Now lets put some emphasis on the cascading of cascading style sheets. As you now know,
styles can be defined in external style sheets, internal style sheets, or inline. There is a fourth
level that we didnt discuss which is the browser default. You dont have any control over that
though. In CSS, an inline style has the highest priority, which means that it will override a style
defined in an internal style sheet, an external style sheet, or the browser default. If an inline style
is not defined then any style rules defined in an internal style sheet would take precedence over
styles defined in an external style sheet. The caveat here is that if a link to an external style sheet
is placed after the internal style sheet in HTML <head>, the external style sheet will override the
internal sheet! Thats a lot to remember! Just keep in mind that style rules defined further down
in the hierarchy override style rules defined higher in the hierarchy.

Figure 19: CSS Priority
These are the basic concepts that you need to understand with regard to CSS. You can use CSS
to define styles for pretty much anything on a web page including backgrounds, text, fonts, links,
lists, images, tables, maps, and any other visible objects.
Note: For a more in-depth treatment of the ArcGIS Server API for JavaScript please refer
to our Building Custom ArcGIS Server Applications with JavaScript. This course is
offered as both a traditional instructor led course and an instructor guided online course.
For more information on this course please visit our website at geospatialtraining.com




Chapter 4: Working with Maps and Layers
Now that you have a taste of ArcGIS Server and the API for JavaScript its time to actually get to
work and learn how to build some great GIS web applications! The material in this chapter will
introduce you to some of the fundamental concepts that define how you create a map and add
information to the map in the form of layers.
Well begin by exploring the basic steps that need to be performed for each application that
uses the ArcGIS Server API for JavaScript. Every application that you create with the API for
JavaScript will need to follow each of these steps. The creation of a map and adding layers to
the map is part of this fundamental process of creating an application. You will learn how to
create an instance of the Map class, add layers of data to the map, and display this information
on a web page. When creating a Map you can supply various parameters that control the initial
extent of the display, the spatial reference, levels of detail, and others. Youll be introduced to
the various parameters that can be used when the map is initially created. Map is the most
fundamental class in the API as it provides the canvas for your data layers and any subsequent
activities that occur in your application. However, your map is useless until you add layers of
data. There are several types of data layers that can be added to a map including tiled,
dynamic, feature, and others. Youll learn more about these layers in this chapter.
Basic Steps for Creating an Application with the ArcGIS Server API for JavaScript
There are four steps that you will need to follow to add a map to your web application. These
steps will always need to be performed if you intend to have a map as part of your application.
Ill briefly highlight each of the steps and then well examine each in greater detail. In a nutshell
the four steps are as follows:
1. Reference the ArcGIS Server API for JavaScript and CSS files
2. Create a container for the map
3. Create an initialization script that performs initial setup operations
4. Call dojo.addOnLoad()
That is a just a brief description of what needs to be done.
Step 1: Reference the ArcGIS Server API for JavaScript
The first thing you need to do in any application that you develop with the ArcGIS Server API for
JavaScript is to add a reference to the API and associated Dojo style sheets.

The style sheet, as you learned in Chapter 3, is used primarily for the graphic elements of the
application and any supporting Dojo widgets and is enclosed within a <link> tag as you can see
in the code example below. Please note that you can place all the text you see in this code
example on a single line rather than dividing it into two lines. Ive used two lines here to make
it easier to read.

As youll recall, the ArcGIS Server API for JavaScript is built directly on the Dojo JavaScript
framework. Dojo comes with four pre-defined themes that control the look of user interface
widgets that are added to your application. The four themes include claro, tundra, soria, and
nihilo. In the code example above we are referencing the tundra theme.

Dojo.org provides a theme tester that you can use to get a feel for how each of the themes
affect the display of Dojo widgets. The theme tester is located at:
http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.html

Figure 20: Dojo Theme Tester
You will also need to reference the ArcGIS Server API for JavaScript from within a <script> tag.
Any <script> tags need to be defined inside the <head> tag of your web page. You must add a
reference to the API for JavaScript along with a reference to the Dojo CSS theme for every
mapping application that you build with the ArcGIS Server API for JavaScript. The reference to
the API is absolutely necessary as it provides a link to all the objects provided by the API. In
order to use any of the objects in the API you must provide this reference. The code example
below shows the reference to the API along with the <link> element which references the style
sheet. As of this writing in early 2012, the current version of the AGIS API for JavaScript is 2.6.
The version is referenced at the end of the URL provided in the src attribute. This version will
change over time as new releases are made available. You can obtain information on the
current version release at http://help.arcgis.com/en/webapi/javascript/arcgis/.

Step 2: Create a container for your map
The map needs to be displayed somewhere on a web page, and the best way to accomplish this
is through an HTML <div> tag which acts as a container for the map. The <div> tag needs to be
placed somewhere inside the <body> tag. Please also note that you need to use the ID
attribute to assign a unique name to your map container as it will be referenced elsewhere in
your code. Notice in the code example below that an ID of map has been assigned to this
container. This ID will be used later in your JavaScript functions to reference the map. Also
notice that we are referencing the claro Dojo theme. Since the reference is placed inside the
<body> tag all widgets will have this theme applied.

Step 3: Create an initialization script that creates an instance of Map
In this step youll get your first look at a JavaScript function. We examined functions briefly in
Chapter 3, but well go into more detail now. JavaScript functions are blocks of code that are
executed as the result of some type of event that has occurred in the application. This could be
something as simple as a map click or dragging the mouse in a panning action. These are
known as user generated events. Application generated events differ in that they are triggered
by the application. The initialization script is executed as the result of an application event that
fires after all the elements of an HTML page have loaded when initially displayed in a browser.

In this step you will create an initialization function that creates the map, adds layers, and
performs any other startup routines. You will use the ID that you assigned to your <div> tag in
this step to place the newly created map inside the <div> container.
In the code example below you will see a code block that demonstrates a typical initialization
script. Obviously before you can do anything you must create a map object. This is
accomplished through a series of steps all of which are wrapped inside a JavaScript <script> tag.
Inside this <script> tag is an initialization function called init( ). Its also common practice to
name the initialization function initialize(). The function name can be anything you wish that
meets the JavaScript rules for function naming, but for the sake of this example were simply
calling it init( ). Youll notice that the first line inside the <script> tag is
dojo.require(esri.map); The ArcGIS API for JavaScript is built on top of Dojo so you use
dojo.require to import resources for your application. In this case we need to access the ability
to create a map which is provided through the esri.map resource.
Most of the work of creating the initial map and layers is accomplished inside the init( )
function. Our first order of business inside init( ) is to create a new map. This is done through
the line map = new esri.Map(map). Remember in Step 2 we added a <div> tag inside the
body of our web page and gave it an ID of map. What this line of code does is create a new
map and place it inside our <div> container which contains an ID of map.
After creating a map, we need to add layers of geographic data to the map. Well cover adding
data layers to your map later in the chapter but for now this is an example of adding a layer of
GIS data to the application that references a map service.
Finally, outside the init( ) function we call dojo.addOnLoad(init) which initiates the init( )
function after the elements of the web page have loaded. The dojo.addOnLoad(init) function is
the subject of the final step in our initialization process.

Step 4: Call dojo.addOnLoad()
The final step in the process is to use the dojo.addOnLoad() function to trigger the execution of
our initialization function. This function runs only after all HTML page elements for our
application have been loaded. This is important because it ensures that any and all HTML
elements can be used by our initialization function. Without this function we could not be
certain that all elements on the page are available to the function and thus errors could occur.
Refer back to the code example above to see the dojo.addOnLoad() function.
Summary
To summarize, for every ArcGIS Server API for JavaScript application that you create you will
need to follow these four steps. Your application should appear similar to the code that you
see below. Each step and its associated code reference are displayed.


Loading this file in a web browser will produce a map of world population as seen in the figure
below.


Figure 21: Creating a Map
Creating a Map
In the four step process described above we introduced the process that youll need to follow
for each application that you build with the ArcGIS Server API for JavaScript. In step 3 you
learned how to create an initialization JavaScript function. The purpose of the initialization
script is to create your map, add layers, and perform any other setup routines necessary to get
your application started. Creating a Map is invariably one of the first things that youll do and in
this section well take a closer look at the various options you have for creating an instance of
the Map class.
In object-oriented programming the creation of a class instance is often done through the use
of a constructor. A constructor is a function that is used to create or initialize a new object. In
this case the constructor is used to create a new Map object. Constructors frequently take one
or more parameters that can be used to set the initial state of an object.

Including Resources
However, before you can call the constructor for a Map you must first reference the resource
that provides the map. This is accomplished through the use of dojo.require(). Dojo.require() is
used to import resources into your web page. Various resources are provided by the API for
JavaScript including the dojo.require(esri.map) resource which must be provided before you
can create a map or work with geometry, graphics, and symbols. Once a reference to the
resource has been provided you can use the Map constructor to create the Map.

The most commonly used resources are listed in the table below.
Resource Use for:
esri.map Map, geometry, graphics, and symbols
esri.layers.agsdynamic ArcGISDynamicMapServiceLayer
esri.layers.agstiled ArcGISTiledMapServiceLayer
esri.tasks.find Find task
esri.tasks.geometry Geometry task
esri.tasks.gp Geoprocessing task
esri.tasks.identify Identify task
esri.tasks.locator Locator task
esri.tasks.query Query task
esri.toolbars.draw Draw
esri.toolbars.navigation Navigation

The Map Constructor
The constructor for the Map class is shown below where divID is a reference to the container
for the map (usually a <div>) and the options specify one or more optional parameters such as
the initial map extent. Take note of the question mark that follows options in the constructor
signature. This simply indicates that this is an optional parameter. Therefore, the only
parameter that you must pass to the constructor is the divID

esri.map(divID, options?)
When creating a new object using a constructor in JavaScript you will need to use the new
keyword as seen in the Map constructor example below. The code example also assigns this
new Map object to an object variable called map. This map variable holds a reference to the
newly created map.

The Map constructor can be passed two parameters including the container where the map
should reside and various options for the map.
A <div> ID is a required parameter for the constructor and is used to specify the container for
the map. This is illustrated in the figure below. When creating a new instance of the Map class
it is required that you provided a reference to the <div> tag that will serve as the container for
your map. This is done by passing in the ID of the <div> tag (in this case its map).

In addition, you can also pass in multiple options that control various aspects of the map
including the initial extent, display of navigation controls, graphic display during panning,
control of the slider, levels of detail, and more.
Lets take a closer look at how options are specified in the map constructor. Options, the
second parameter in the constructor, are always enclosed with brackets. Inside the brackets
each option has a specific name and is followed by a colon and then the data value that
controls the option. In the event that you need to submit multiple options to the constructor,
each option is separated by a comma. Below you see a code example showing how options are
submitted to the Map constructor. In this case we are defining options for the initial extent,
slider, and nav.

Setting the initial extent is probably the most commonly used option of those available. This
parameter controls the initial geographic extent of the map, but there are several other options
that you can set including:
layer The base layer used to initialize the map
nav True/False value indicating whether to display pan buttons on the map
displayGraphicsOnPan True/False value indicating whether graphics should be
displayed during panning.
slider True/False value indicating if the zoom slider should be displayed
The Spatial Reference
The MXD or MSD used to create a map service defines the spatial reference that will be used
for that service. Dynamic map service layers have the ability to project data on the fly to that of
other map services in your application. So, if you are using a WGS 84 base map from ArcGIS
Online, your dynamic UTM service will overlay the base map using on the fly projection. Map
service projection on the fly does not work with cached map services. So for those map
services that you are going to cache you need to change the projection of the map to the
projection of the other services you are going to mash up with.
Working with Map Service Layers
A map without data layers is sort of like an artist with a blank canvas. The data layers that you
add to your map give it meaning and set the stage for analysis. There are two primary types of
map services that provide data layers that can be added to your map: dynamic map service
layers and tiled map service layers.
Dynamic Map Services
Dynamic map service layers reference map services that create a map image on the fly and then
return the image to the application. This type of map service may be composed of one or more
layers of information. For example, the Demographics map service displayed in the figure
below is composed of 9 different layers representing demographic information at various levels
of geography.

Figure 22: Demographics Map Service

While they can take somewhat longer to display in a client application since they must be
generated on the fly, dynamic map service layers are more versatile than tiled map service
layers in that you can control the features displayed through layer definitions, set the visibility
of various layers within the service, and define temporal information for the layer. For
example, in the Demographics map service layer detailed above you might elect to only display
Census Block Groups in your application. This is the type of versatility provided by dynamic
map service layers that you dont get with tiled map service layers.


Figure 23: Dynamic Map Service Layers
Tiled map service layers (see Figure X) reference a pre-defined cache of map tiles instead of
dynamically rendered images.

Figure 24: Tiled (Cached) Layer
Tiled Map Service Layers
The easiest way to understand the concept of tiled map services is to think about a grid that has
been draped across the surface of a map. Each cell within the grid has the same size and will be
used to cut the map into individual image files called tiles. The individual tiles are stored as
image files on a server and retrieved as necessary depending upon the map extent and scale.
This same process is often repeated at various map scales. The end result is a cache of tilesets
that have been generated for various map scales. When the map is displayed in the application
it will appear to be seamless even though it is composed of many individual tiles.

Figure 25: Map Tiles
These tiled, or cached, map layers are often used as base maps including imagery, street maps,
topographic maps, and others. Tiled map services tend to display somewhat faster since they
dont have the overhead of creating images on the fly each time there is a request for a map.
Operational layers are then draped on top of the tiled base maps and these are often dynamic
layers. While they can be somewhat slower in terms of performance, dynamic map service
layers have the advantage of being able to define their appearance on the fly.
Using the Layer Classes
Using the Layer classes from the API for JavaScript you can reference map services hosted by
ArcGIS Server and other map servers. Referring to the object model diagram in Figure X you
can see that all layer classes inherit from the Layer base class. The Layer class has no
constructor so you cant specifically create an object from this class. This class simply defines
properties, methods, and events that are inherited by all sub-classes of Layer.
DynamicMapServiceLayer, TiledMapServiceLayer, and GraphicsLayer all inherit directly from
the Layer class. DynamicMapServiceLayer and TiledMapserviceLayer also act as base classes.
DynamicMapServiceLayer is the base class for dynamic map services while
TiledMapServiceLayer is the base class for tiled map services. Chapter <X> is devoted entirely
to graphics and the GraphicsLayer so well save our discussion of this layer type for later in the
book. Layer, DynamicMapServiceLayer, and TiledMapServiceLayer are all base classes meaning
that you cant specifically create an object from these classes in your application.

Figure 26: Layer OMD
Tiled Map Service Layers
ArcGISTiledMapServiceLayer
As I mentioned, tiled map service layers reference a cache of pre-defined images that are tiled
together to create a seamless map display. These are often used as base maps.

Figure 27: Tiled Map Service Layers
The ArcGISTiledMapServiceLayer class is used when referencing a tiled (cached) map service
exposed by ArcGIS Server. Since this type of object works against a tiled set of maps that have
been cached, performance is often improved. The constructor for ArcGISTiledMapServiceLayer
takes an URL pointer to the map service along with options that allow you to assign an ID to the
map service, and control transparency and visibility. In the code example below, notice that
the constructor for ArcGISTiledMapServiceLayer takes a parameter that is a URL to a map
service. After an instance of a layer has been created it is then added to the map using the
Map.addLayer() method which accepts a variable that contains a reference to the tiled map
service layer.


ArcGISTiledMapServiceLayer is used primarily for the fast display of cached map data. You can
also control the levels at which the data will be displayed. For instance, you may want to
display data from a generalized ArcGISTiledMapService showing interstates and highways while
your users are zoomed out at levels 0-6 and then switch to a more detailed
ArcGISTiledMapService once the user zooms in further. You can also control the transparency
of each layer added to the map.
VETiledLayer and OpenStreetMapLayer
The VETiledLayer and OpenMapStreetLayer classes are used to load a Bing Maps or Open
Street Map layers respectively. The tilesets for these layers are not pulled from an ArcGIS
Server instance but rather servers hosted by Microsoft and Open Street Map. The constructor
for both classes takes a single parameter that defines the options for the layer. For
VETiledLayer the options would include a Bing Maps key that you can obtain from the Bing
Maps website.
Options for the OpenStreetMapLayer constructor include a transparency value, display levels,
id, visibility, and the tile servers to use. The code example below shows the creation of an
OpenStreetMapLayer object with various options passed in.

The options for the OpenStreetMapLayer constructor are optional so you could simply call the
constructor without passing in any options.


Dynamic Map Service Layers
ArcGISDynamicMapServiceLayer
As the name suggests, the ArcGISDynamicMapServiceLayer class is used to create dynamic
maps served by ArcGIS Server. Just as with ArcGISTiledMapServicelayer the constructor for
ArcGISDynamicMapServiceLayer takes a URL that points to the map service along with optional
parameters used to assign an ID to the service, determine the transparency of the map image
and a visibility option which sets the initial visibility of the layer to true or false. The class name
ArcGISDynamicMapServiceLayer can be somewhat misleading. Although it appears to
reference an individual data layer this is in fact not the case. It refers to a map service rather
than a data layer. Individual layers inside the map service can be turned on/off through the
setVisibleLayers( ) method.


Figure 28: Dynamic Map Service Layers
Creating an instance of ArcGISDynamicMapServiceLayer will look very similar to
ArcGISTiledMapServiceLayer. The code example below illustrates this. The constructor accepts
a URL that points to the map service. The second parameter defines the optional parameters
that you can supply to control transparency, visibility, and image parameters.

With an instance of ArcGISDynamicMapServiceLayer you can perform a number of operations.
Obviously you can create maps that display the data in the service, but you can also query data
from layers in the service, control feature display through layer definitions, control individual
layer visibility, set time related information, export maps as images, control background
transparency, and more.
After a new instance has been created you need to add it to your map so that it will be visible.

Adding Layers to the Map
The Map.addLayer() method takes an instance of a layer (ArcGISDynamicMapServiceLayer or
ArcGISTiledMapServiceLayer) as the first parameter, and an optional index that specifies where
it should be placed. In the code example below we create a new instance of
ArcGISDynamicMapServiceLayer pointing to a URL for the service. We then call
Map.addLayer(), passing in the new instance of the layer. The layers in the service will now be
visible on the map. The addLayers() methods takes an array of layer objects and adds them all
at once.

Figure 29: Adding a Layer
In addition to being able to add layers to a map you can also remove layers from a map using
Map.removeLayer() or Map.removeAllLayers().
Practice Time - Hello Map
It is a long standing tradition of programming books to have you write an incredibly simply
Hello World application to get started. Well, were going to start our own similar tradition by
creating a Hello Map application! It wont be quite as simple as most Hello World
applications but if youve understood the previously described basic steps for creating an
application with the API for JavaScript then you shouldnt have too much trouble.
Getting and Setting the Map Extent
One of the first things youll want to master is getting and setting the map extent. By default
the initial extent of a map within your application is the extent of the map when it was last
saved in the map document file (.mxd) used to create the map service. In some cases this may
be exactly what you want, but in the event that you need to set a map extent other than the
default you have several options. The first and easiest method of setting the initial map extent
is to specify the coordinates directly in the constructor for the Map object.
The initial extent of the map is not a required parameter, and thus if you leave out this
information the map will simply use the default extent. This is shown in the first code example
below where only the ID of the container is specified.

To set the initial extent in the constructor you simply specify an extent and use this extent as an
option in the Map constructor. The code example below illustrates this process. A new
instance of the Extent class is created and stored in a variable called initExtent. This variable
containing the extent is then used in the constructor for the Map object.

Rather than setting the initial extent through the constructor you could use the Map.setExtent
method seen in the code example below.

There may be times when you are using multiple map services in your application. In this case,
setting the initial map extent can be done either through the constructor for your map or by
using the Map.fullExtent method on one of the services. For example, it is common to use a
map service that provides base layer capabilities containing aerial imagery along with a map
service containing your own local operational data sources. The code example below uses the
fullExtent() method.

The current extent of a map can be obtained either through the Map.extent property or the
onExtentChange event. Please note that the Map.extent property is read-only so dont attempt
to set the map extent through this property.
Setting the Visible Layers from a Map Service
You can control the visibility of individual layers within a dynamic map service layer using the
setVisibleLayers() method. This only applies to dynamic map service layers, not tiled map
service layers. This method takes an array of integers corresponding to the data layers in the
map service. This array is 0 based, so the first layer in the map service occupies position 0. In
our Demographics map service illustrated in the figure below, Demographics/ESRI_Census_USA
occupies index 0. Therefore, in the event that wed like to display only the Census Block Points
and Census Block Groups from this service we could use setVisibleLayers() as seen in the code
example below.




Setting a Definition Expression
In ArcGIS Desktop you can use a Definition Expression to limit the features in a data layer that
will be displayed. A definition expression is simply a SQL query against the columns and rows in
a layer. Only the features whose attributes meet the query are displayed. For example, if you
only wanted to display cities with a population greater than 1 million the expression would be
something like POPULATION > 1000000. The ArcGIS Server API for JavaScript contains a
setLayerDefinitions( ) method that accepts an array of definitions that can be applied against
ArcGISDynamicMapServiceLayer to control the display of features in the resulting map. The
code example below shows how this is done. You first create an array that will hold multiple
where clauses which will serve as the definition expressions for each layer. In this case we are
defining layer definitions for the first and sixth layer. The array is zero based so the first array is
at index 0. The where clauses are placed into the array and then passed into the
setLayerDefinitions method. ArcGIS Server then renders the features that match the where
clauses for each layer.


Map Navigation Map Extent, Zooming, and Panning
Now that you know a little about maps and the layers that reside within those maps its time to
learn how to control map navigation in your application. In most cases your users will need to
be able to navigate around the map through panning and zooming. The ArcGIS Server API for
JavaScript provides a number of user interface widgets and toolbars that you can use to allow
your user to change the current map extent through zooming and panning. Map navigation can
also occur through keyboard navigation and mouse navigation. In addition to these user
interface components and hardware interfaces, map navigation can also be controlled
programmatically.
Map Navigation Widgets and Toolbars
The simplest way to provide map navigation control to your application is through the addition
of various widgets and toolbars. By default, when you create a new map and add layers a zoom
slider (see figure x below) is included with the map. This slider allows the user to zoom in and
out on the map. You dont have to do anything programmatically to have the zoom slider
appear on your map. It is present by default.

Figure 30: Navigation Widget
However, you can remove the slider if necessary from your application simply by setting the
slider option to false when creating an instance of the Map object.


You can also add pan buttons that will pan the map in the direction that the arrow points when
clicked. By default pan buttons will not appear on the map. You must specifically set the nav
option to true when creating your Map object.


Figure 31: Pan Buttons
The ArcGIS API for JavaScript also gives you the ability to add several types of toolbars to your
application including a navigation toolbar containing buttons for zooming in and out, panning,
full extent, next extent and previous extent. The topic of toolbar creation is covered in detail in
a later chapter so well save that discussion for later. I do want to make you aware of the
existence of this toolbar though. Creating a toolbar with the API for JavaScript is not a user
interface component that you just drop into your application, but it is a fairly simple process
to add these toolbar to your application.

Figure 32: Navigation Toolbar
Controlling Map Navigation with the Mouse and Keyboard
Users can also control map navigation with the mouse and/or keyboard devices. By default,
users can do the following:
Drag the mouse to pan
Mouse Scroll Forward to zoom in
Mouse Scroll Backward to zoom out
SHIFT + Drag the mouse to zoom in
SHIFT + CTRL + Drag the mouse to zoom out
SHIFT + Click to recenter
Double Click to Center and Zoom in
SHIFT + Double Click to Center and Zoom in
Use arrow keys to pan
Use + key to zoom in a level
Use - key to zoom out a level
These options can be disabled using one of several Map methods. For example, to disable scroll
wheel zooming you would use the Map.disableScrollWheelZoom() method.
Note: For a more in-depth treatment of the ArcGIS Server API for JavaScript please refer
to our Building Custom ArcGIS Server Applications with JavaScript. This course is
offered as both a traditional instructor led course and an instructor guided online course.
For more information on this course please visit our website at geospatialtraining.com


Chapter 5: Handling Events

In the world of programming, events are actions that take place within an application.
Normally these events are triggered by the end user and can include things like mouse clicks,
mouse drags, keyboard actions, and others, but can also include the sending and receiving of
data, component modification, and others.
Not all web browsers handle events in the same way. No surprise there right? Dojo normalizes
these events according to the W3C standard so that you dont have to worry about how
different browsers handle various events. The dojo.connect() method is used to connect events
that happen in your application to the code that will run in response to these events.
The ArcGIS Server API for JavaScript is an asynchronous API that connects event listeners with
event handlers. So the obvious question you may be asking now is what is an asynchronous API
and what does it mean in the context of my mapping application? Basically an asynchronous
API just means that not every method that you call on an object will immediately return results.
This is often the case with geoprocessing tasks that take awhile to execute and return results.
In this case, when the result has been generated on the server it is returned to the application
and executed by a handling function whose specific task is to process the results when they
become available.
The diagram below illustrates this process. Listeners are responsible for monitoring the
application for these events and then triggering a handler function that responds to the event.
Multiple events can be registered to the same listener.

Figure 33: Connecting Events to Handlers
Connecting Events to Handlers
As youll recall, the ArcGIS Server JavaScript API is built on top of Dojo. With Dojo, events are
registered to handlers through the dojo.connect() method. This method takes three
parameters. Lets take a look at the code below to get a better understanding of how events
are registered.

We call the dojo.connect() method with parameters including map, onMouseMove, and
showCoordinates. The first two parameters indicate the object and the event that we would
like to register. In this case that means we are registering the onMouseMove event found on
the Map object. This event is fired every time the mouse moves within the confines of the
map. The final parameter, showCoordinates, indicates the listener that we are registering this
event with. Therefore, each time the onMouseMove event on the Map object is fired, it will
trigger the showCoordinates() function which will run and report the current extent of the map.
Although the events and the handlers they are registered to will change depending upon your
circumstance, the method of registration is the same.
Disconnecting Events and Handlers
You can also assign a variable to the connection as seen in the code example below.

This comes in handy later when you want to release the handler when it is no longer needed in
your application or when the application closes. It is important to remove the connections
between events and listeners when your application closes. Failure to do so can cause memory
leaks. To remove an event listener you can call dojo.disconnect() when the Map.onUnload() event
occurs. The Map.onUnload() event is fired when the page is refreshed or closed. A code example below
illustrates this process of disconnecting an event from a handler.

There are many different events that are available on objects in the ArcGIS Server API for
JavaScript. However, it is important to keep in mind that you do not have to register every
event with a listener. Only those events that are necessary for your application should be
registered. When an event occurs that hasnt been registered with a listener the event is
simply ignored.
Passing Information to an Event
Information is passed into the events in the form of parameters. For instance, the
Map.onClick(event) event is passed an Event object which contains information specific to the
event that has occurred. These Event objects are dynamic in that they contain different
information depending upon the event that was fired. For instance, the Event object passed
into Map.onClick() contains information about the x,y location of the point that was clicked on
the map. Not all events are passed an Event object. For instance, the Map.onLayerAdd(layer) is
passed a Layer object containing information about the layer that was added to the map.
Common ArcGIS Server API for JavaScript Events
Many of the classes in the JavaScript API have events, but certain classes like Map have more
commonly used events. For instance, the Map class has all of the events you see on the object
model diagram below plus more. Most of these events fall within several groups related to
zooming, panning, and layer events. There are also events triggered when the map extent
changes, a layer has been added to the map, and when the user has clicked the map. Each of
these events can have a handler that responds to having been fired.
Map.onLoad and Map.onUnload
Weve already discussed Map.onUnload() which is fired anytime the page refreshes or is closed.
The Map.onLoad() event is fired after an initial layer has been added to the map. The graphics
layer which holds graphics for your application is also loaded at this time. At this point you can
interact with the map in your code.

Map Events Related to Clicking the Map
The Map.onClick() and Map.onDblClick() events are fired when the user clicks or double clicks
the map. An application might elect to display the coordinates where the user clicked the map
or perhaps create a graphic at that point. The Map.onClick() event can be used to handle these
scenarios.
Map Events Related to Layers
A number of events related to layers can be found on the Map object. These include events
that fire when a layer is added, removed, and reordered. Events related to layers include
Map.onLayerAdd(), Map.onLayerRemove(), Map.onLayerReorder(), Map.onLayersRemoved(),
and a few others.
Map Events Related to the Mouse
There are a lot of events that can happen related to the mouse and the Map object. Some fo
the more commonly used mouse events include onMouseDown, onMouseUp, onMouseOver,
onMouseDrag, onMouseWheel, and several others. Each corresponds to some action the user
has initiated with the mouse.
Zoom and Pan Events
Zoom and pan operations are common place in a mapping application and the API contains
several events that fire when these take place. These events include onExtentChange(),
onPanStart(), onPan(), onPanEnd(), onZoomStart(), onZoom(), and onZoomEnd().
Note: For a more in-depth treatment of the ArcGIS Server API for JavaScript please refer
to our Building Custom ArcGIS Server Applications with JavaScript. This course is
offered as both a traditional instructor led course and an instructor guided online course.
For more information on this course please visit our website at geospatialtraining.com







Chapter 6: Adding Graphics to the Map
In addition to traditional map service layers exposed by ArcGIS Server an application can also
draw point, line, and polygon graphics in a separate layer on the map. This layer, called a
GraphicsLayer, stores all graphics associated with your map. In Chapter 4 we discussed the
various types of layers including dynamic map service layers and tiled map service layers. Just
as with these other types of layers, GraphicsLayer also inherits from the Layer class. Therefore,
all the properties, methods, and events found on the Layer class will also be present on
GraphicsLayer.
Graphics are displayed on top of any other layers that are present in an application. These
graphics can be created by users or drawn by the application as results of tasks that have been
submitted to ArcGIS Server. For example, a business analysis application might provide a tool
that allows the user to draw a free-hand polygon representing a potential trade area. The polygon
graphic would be displayed on top of the map, and could then be used as input to a
geoprocessing task that pulls demographic information pertaining to the potential trade area.

Figure 34: Graphics
Many ArcGIS Server tasks return their results as graphics. The Query Task can perform both
attribute and spatial queries. The results of a query are then returned to the application in the
form of a FeatureSet object which is simply an array of graphics. Application code is then used
to loop through this FeatureSet and plot each graphic on the map. Perhaps youd like to find and
display all land parcels that intersect the 100 year flood plain. A Query Task could perform the
spatial query and then return the results to your application where theyd then be displayed as
polygon graphics on the map.
The Four Parts of a Graphic
A graphic is composed of four items: geometry, symbol, attributes, and an InfoTemplate. Most
people intuitively understand the idea that a graphic has a geometric representation that describes
where it is located. The geometry along with a symbol defines how the graphic is displayed.
However, a graphic can also have attributes which are name-value pairs that describe the graphic
as well as an Info Template that defines the format of the InfoWindow that appears when a
graphic is clicked. After creation, graphic objects must be stored inside a GraphicsLayer object
before they can be displayed on the map. This GraphicsLayer object functions as a container for
all graphics that will be displayed.

Figure 35: Parts of a Graphic
All elements of a graphic are optional. However, the geometry and symbology of a graphic are
almost always assigned. Without these two items there would be nothing to display on the map,
and there isnt much point in having a graphic unless youre going to display it.
Below you will see a code example illustrating the typical process for creating a graphic and
adding it to the graphics layer. In this case we are applying the geometry of the graphic as well
as a symbol for depicting the graphic. However, we havent specifically assigned attributes or an
InfoTemplate to this graphic.

Figure 36: Coding Graphics
Creating Geometry for Graphics
Graphics will almost always have a geometry component which is necessary for placement on
the map. These geometry objects can be points, multi-points, polylines, polygons or extents and
can be created programmatically through these objects or they can be returned as output from a
task such as a query.
Before creating any of these geometry types the esri.geometry resource needs to be imported.

The geometry resource contains classes for Geometry, Point, Multipoint, Polyline, Polygon, and
Extent.
Geometry is the base class which is inherited by Point, MultiPoint, Polyline, Polygon, and Extent
classes. The primary method of importance on this class is setSpatialReference() which allows
you to set the spatial reference for a geometry.

Figure 37: Graphic Geometry



The Point class defines a location by an X and Y coordinate, and can be in either map units or
screen units. Multipoint, Polyline, Polygon, and Extent classes can be used to create their
respective geometries.
Symbolizing Graphics
Each graphic that you create can be symbolized through one of the various symbol classes found
in the API. Point graphics are symbolized by the SimpleMarkerSymbol class and the available
shapes include circle, cross, diamond, square, and X. It is also possible to symbolize your points
through the PictureMarkerSymbol class which uses an image to display the graphic. Linear
features are symbolized through the SimpleLineSymbol class and can include solid lines, dashes,
dots, or a combination. Polygons are symbolized through the SimpleFillSymbol class and can be
solid, transparent, or cross hatch. In the event that youd prefer to use an image in a repeating
pattern for your polygons the PictureFillSymbol class is available. Text can also be added to a
GraphicsLayer and is symbolized through the TextSymbol class.

Figure 38: Graphic Symbology
Points or multi-points can be symbolized through the SimpleMarkerSymbol class which has
various properties that can be set including the style, size, outline, and color. Style is set through
the SimpleMarkerSymbol.setStyle( ) method which takes accepts a constant value as a parameter
that corresponds to the type of symbol that is drawn (circle, cross, diamond, etc). Point graphics
can also have an outline which is created through the SimpleLineSymbol class.



Linear features are symbolized with the SimpleLineSymbol class and can be a solid line or a
combination of dots and dashes. Other properties of line symbols include color as defined with
dojo.color and a width property for setting the thickness of your line.


Polygons are symbolized with the SimpleFillSymbol class which allows for the drawing of
polygons in solid, transparent, or cross hatch patterns. Polygons can also have an outline
specified by a SimpleLineSymbol object.


Symbolizing Graphics with Renderers
A renderer can be used to define a set of symbols for graphics contained within a GraphicsLayer.
These symbols can have different colors and/or sizes based on an attribute. The four types of
renderer in the ArcGIS Server API for JavaScript include SimpleRenderer,
ClassBreaksRenderer, UniqueValueRenderer, and TemporalRenderer. Well examine each type
of renderer.
The rendering process will be the same regardless of the type of renderer you use. You first need
to create an instance of the renderer, define the symbology for the renderer, and finally, apply the
renderer to the GraphicsLayer. In the event that you dont want to apply the same renderer to all
graphics in the GraphicsLayer you will need to create multiple GraphicsLayer objects to
organize your graphics. This rendering process is illustrated below.


Figure 39: Rendering Process
The code example below shows the basic programmatic structure for creating and applying a
renderer to a GraphicsLayer.

The simplest type of renderer is the SimpleRenderer which simply applies the same symbol for
all graphics.
A UniqueValueRenderer can be used to symbolize graphics based on a matching attribute which
is typically a field containing string data. For example, if you have a roads feature class you
might want to symbolize each feature based on road type. Each road type would have a different
symbol. The code example on this slide shows how you would programmatically create a
UniqueValueRenderer and add values and symbols to the structure.

A ClassBreaksRenderer works with data stored as a numeric attribute. Each graphic will be
symbolized according to the value for that particular attribute in accordance with breaks in the
data. The breaks define the values at which the symbol will change. For example, with a Parcel
Feature Class you might want to symbolize parcels based on values found in the PropertyValue
field. Youd first want to create a new instance of ClassBreaksRenderer and then define the
Create Renderer
Define Symbology
Apply to GraphicsLayer
breaks for the data. The Infinity and -Infinity values can be used as the lower and upper
boundaries for your data if needed as seen in the code example below where we use the
Infinity keyword to signify a class break of any values greater than 250,000.

Assigning Attributes to Graphics
The attributes of a graphic are the name value pairs that describe that object. In many cases
graphics are generated as the result of a task operation such as QueryTask. In these cases a
geometry object is composed of both geometry and attributes and youd then need to symbolize
each graphic accordingly. The field attributes associated with the layer is the attributes for the
graphic. The attributes returned can be limited through the use of the outFields property. If
your graphics are being created programmatically then youll need to assign the attributes in your
code using the Graphic.setAttributes() method seen in the code example below.

Figure 40: Graphic Attributes

Displaying Graphic Attributes in an InfoTemplate
In addition to attributes a graphic can also have an InfoTemplate that defines how the attribute
data is displayed in a pop-up window, also known as an Info Window. A point attribute variable
is defined in the code example you see below and contains name (key) value pairs. In this
particular case we have keys that include address, city, and state. Each of these names or keys
has a value. This variable is the third parameter in the constructor for a new point graphic. An
InfoTemplate defines the format of the Info Window that appears and contains a title and an
optional content template string. Content for the template is added with the
InfoTemplate.content property as seen in the code examples below.
Content for an InfoTemplate can be defined as a string, HTML, or a placeholder. The most basic
type of content is simply a string of characters that is displayed as plain text in the InfoWindow.

An InfoTemplate can also be defined using HTML tags. This is a much more flexible way of
adding content to your InfoWindow because it enables you to embed links, images, video, audio,
and pretty much any other type of HTML tag.

Finally, you can also use placeholders to define content. Placeholders are created using the
format ${FIELD_NAME} to define an attribute value that should be displayed in a particular
placeholder. The attribute defined inside the placeholder must be the exact column name from a
layer.


Figure 41: Graphic InfoTemplate


Figure 42: InfoTemplate Example
Info Windows
An infoTemplate, as you learned in the last section, is used to define how content will be
displayed in an InfoWindow. Both the title and content of the window are defined with an
InfoTemplate. Now well turn our attention to the actual InfoWindow. In addition to displaying
the attributes of a feature and other text, an InfoWindow can contain charts, pictures, video, and
pretty much anything else that can be defined with HTML tags. A single InfoWindow is
associated with a Map object and contains both a title as well as content.

Figure 43: Setting the Title and Content
An InfoWindow is most commonly associated with a graphic and by default is displayed when
clicked. However, an InfoWindow is associated with the Map so it can be displayed is response
to other events such as the completion of a query or some other action not associated with a
graphic.
Displaying the InfoWindow
The InfoWindow is displayed by calling the InfoWindow.show() method as seen in the code
example below. Note that the InfoWindow is a property of the Map object and is accessed with
dot notation like any other property. Once youve obtained an instance of the InfoWindow you
can set the title, content, and show the window.

Customizing the InfoWindow
By default the InfoWindow will appear as weve seen in the figure below with a light grey
background, title in bold at the top of the window, content below, and an X in the upper right
hand corner that closes the button. However, there may be times when youd like to alter the
look of the InfoWindow. This can be accomplished by adding Dojo dijits, altering the CSS for
the window, using an image as the background for the window, or the creation of a custom
window.

Figure 44: InfoWindow
The Dojo TabContainer dijit is often used to organize several pieces of information inside a
single InfoWindow. Other Dojo dijits can also be used to enhance the information that is
displayed. The figure below combines a TabContainer dijit along with a Dojo chart to create an
attractive InfoWindow.

Figure 45: Adding a Chart to an InfoWindow
The InfoWindow can also be simplified by loading the InfoWindowLite resource using
dojo.require. This will create a simpler InfoWindow like the one you see below.

Figure 46: Simplified InfoWindow
Using CSS the InfoWindow can then be styled to an even greater degree. The CSS code below
would produce an InfoWindow with a dark border color and a white-green gradient applied to
the background.


Figure 47: Styling an InfoWindow
In addition to using CSS to style an InfoWindow you can also create your own custom
InfoWindow using a background image. This requires that a .png format image be created for
the background, close button and pointer using some sort of photo-editing program. ESRI also
provides a .png file
(http://help.arcgis.com/en/webapi/javascript/arcgis/help/jshelp/images/claroinfowindow.png) that
can be downloaded and modified.
For even more advanced customization of InfoWindows you can also extend the
InfoWindowBase class. However, this will require that you implement several required
methods, properties, and events to ensure that the custom InfoWindow provides a minimum level
of functionality.
Popups
A new type of information window, introduced at version 2.3 of the API, is the Popup window.
The Popup and PopupTemplate classes were added to the API that gives custom applications the
same experience as pop-ups created using ArcGIS.com. The new Popup window has a more
modern styling than the InfoWindow and also provides additional functionality. In addition to
displaying a title and content, Popup window also provides navigation through selected features,
zooming to the selected feature, highlighting of a selected feature, and the ability to maximize
the window. You can see an example of these new functions in the figure below.

Figure 48: Popup Window
To replace the default InfoWindow with a PopUp window in an application several lines of code
need to be added to the application. First, add the popup stylesheet to the application as seen
below.

Import the popup class module.

Create a new instance of the Popup class. Various options can be defined to change the look and
functionality of the Popup class. These options include the feature highlight symbols for
selected features, x and y offsets for positioning the popup, a zoom factor, and others.

Finally, create the Map and pass in an instance of the popup as an option.

Creating the Graphic
Once the optional geometry, symbology, attributes, and info template have been define a new
Graphic object can be created with these parameters used as input to the constructor for the
Graphic. Notice in the code example below that we create variables for the geometry
(pointESRI), symbology (markerSymbol), point attributes (pointAttributes), and InfoTemplate
(pointInfoTemplate) and then apply these variables as input to the constructor for our new
graphic called pointGraphic. Finally, this graphic is added to the GraphicsLayer.

Adding Graphics to the GraphicsLayer
Before any graphics can be displayed on the map they must added to the GraphicsLayer. Each
map has a GraphicsLayer which contains an array of graphics that is initially empty until you add
the graphics. This layer can contain any type of graphic object meaning that you can mix in
points, lines, and polygons at the same time. Graphics are added to the layer through the add( )
method and can also be removed individually through the remove( ) method. In the event that
you need to remove all graphics simultaneously the clear( ) method can be used. GraphicsLayer
also has a number of events that can be registered including onClick, onMouseDown, and others.


Figure 49: GraphicLayer
Multiple Graphics Layers
In addition to the default GraphicsLayer associated with the Map object, multiple graphics layers
are supported by the API making it much easier to organize different types of graphics. These
graphic layers can easily be removed or added as needed. For example, you can put polygon
graphics representing counties in one graphics layer and point graphics representing traffic
incidents in another graphics layer. To create a new GraphicsLayer use the GraphicsLayer
constructor along with any optional parameters.

Chapter 7: The FeatureLayer: Graphics on Steriods!
The ArcGIS Server API for JavaScript offers a feature layer for working with client-side graphic
features. You should already be familiar with the graphics layer from the previous chpater. The
feature layer inherits from the graphics layer, but offers additional capabilities such as the ability
to perform queries and selections. Feature layers are also used for Web editing.
Feature layers differ from tiled and dynamic map service layers because feature layers bring
geometry information down to the client computer to be drawn by the Web browser. Feature
layers potentially cut down on round trips to the server. A client can request the features it needs,
and perform selections and queries on those features without having to request more information
from the server. Feature layers are especially appropriate for layers that respond to user
interaction, such as a mouse click or hover.
A feature layer honors any definition queries, scale dependencies, and other properties
configured on the layer in the map service. Using a feature layer, you can access related tables,
perform queries, display time slices, work with feature attachments, and do various other useful
things.

A feature layer must reference a layer from either a map service or a feature service. If the
retrieval of geometries and attributes from layer is the only operation to be performed a map
service will suffice. On the other hand feature editing and the use of symbols from the services
source map document require the use of a feature service. For editing, feature layers honor any
feature templates that have been configured in the source map document.
The initial creation of a feature layer also requires that a display mode be selected. Display
modes include snapshot mode, on-demand mode, and selection only mode. The mode specifies
how and when features are transported from the server to the client browser. It is very important
that the mode selected fit both the underlying data of the feature layer as well as the needs of the
application. Because the mode determines when and how features are brought from the server to
the client, the selection of a mode has a large affect on the speed and appearance of the
application.

Snapshot Mode
Snapshot mode retrieves all features from the layer when it is added to the map so you need to
carefully consider the size of your layer before using this mode. Generally you will want to use
this mode only with small datasets. Large datasets in snapshot mode can significantly degrade
the performance of your application. The benefit of snapshot mode is that since all features from
the layer are returned to the client there is no need to return to the server for additional data.
This raises the potential for a significant boost in your application performance. However, it also
raises the potential to significantly degrade performance if not used correctly.
ArcGIS imposes a limit of 1000 features that may be returned at any one time. This number is
configurable through ArcGIS Server administration. Practically though you will want to only
use this mode when youre working with small datasets of no more than a couple hundred
features. Attempting to use snapshot mode with larger datasets can significantly decrease the
performance and responsiveness of an application.
On Demand Mode
On demand mode retrieves features only as needed. Essentially this means that only the features
in the current map extent are returned to the client. As the user navigates to other areas through
zoom or pan operations a new set of features is retrieved from the server and streamed to the
client. This tends to work well with large datasets that wont operate efficiently in snapshot
mode. It does require a round trip to the server to fetch the features each time the extent
changes, but for large datasets this is preferable.
Selection Only Mode
Selection only mode does not initially retrieve features from the server. Instead, features are
returned only when a selection is made on the client. Selected features are streamed to the client
from the server when features are selected. These selected features are then held on the client.
Creating a FeatureLayer
Below you will see a code example detailing how to create a FeatureLayer using its constructor.
With tiled and dynamic layers you simply provide a pointer to the REST endpoint, but with
FeatureLayer you need to point to a specific layer in the service. In this code example we are
creating a FeatureLayer from the first layer. This is indicated by the number 0 which is the first
layer. The constructor for FeatureLayer also accepts options such as the display mode, output
fields, info template, and others. Here, the display mode is set to snapshot which would indicate
that we are probably dealing with a relatively small dataset.

Setting a Definition Expression
Definition expressions are used to limit the features that are displayed on a map. The
FeatureLayer class contains a setDefinitionExpression() method that is used to create the
expression. All features that meet the specified criteria will be returned for display on the map.
Expressions are built using traditional SQL expressions. You can retrieve the currently set
definition expression by using FeatureLayer.getDefinitionExpression which returns a string
containing the expression.
Feature Selection
FeatureLayer also supports feature selection which is simply a subset of features from a layer
that is used for viewing, editing, analysis, or input to other operations. Features are added to or
removed from a selection set using either spatial or attribute criteria and can easily be drawn with
a different symbol than those used in the normal display of a layer. The selectFeatures(query)
method on FeatureLayer is used to create a selection set and takes a Query object as input.
Any definition expression or time definition set on a layer either through the application or on
the layer inside the map document file will be honored. Setting a symbol to use for the selected
features is quite easy and simply involves creating a symbol and then using the
'setSelectionSymbol' method on FeatureLayer. Selected features will automatically be assigned
this symbol. You can opt to define a new selection set, add features to an existing selection set,
or remove features from a selection set. In addition, you can define callback and errback
functions to process the returned features or handle any errors.


Chapter 8: Using Toolbars
As a GIS web application developer you want to focus on building functionality specific to the
application you are constructing. Spending valuable time and effort adding basic GIS functions
such as zooming and panning to your application detract from what should be your primary
focus.
The ArcGIS Server API for JavaScript includes helper classes for adding navigation and drawing
toolbars to your application. In this chapter youll learn how easy it is to add these user
interface components to an application.

Lets start by examining a navigation sample that ESRI has placed on their resource center
website. Open a web browser and go to:
http://help.arcgis.com/en/webapi/javascript/arcgis/demos/toolbar/toolbar_navigation.html

At first glance youd think that the navigation toolbar is simply a user interface component that
you drop into your application. Not exactly. The ArcGIS Server API for JavaScript provides a
toolbar helper class called esri.toolbars.Navigation to assist with accomplishing this task. In
addition, the API also provides a class to handle drawing tasks such as lines and polygons. What
these helper classes do is save you the work of drawing zoom boxes, capturing mouse clicks and
other user initiated events. As any experienced GIS web developer can tell you this is no small
accomplishment. Developing these basic navigation capabilities into the helper classes
provided with the API can easily save dozens of hours of development work.
Adding Toolbars to an Application
There are two basic types of toolbars that you can add to your application using helper classes
provided by the API: navigation and drawing. There is also an editing toolbar that can be used
to edit features through a web browser. Well discuss this toolbar in the Editing Data chapter.
Steps for Creating a Toolbar
As I mentioned on the previous slide the navigation and draw toolbars are not simply user
interface components that you can drop into your application. They are helper classes and
there are several steps that you need to take to actually create your toolbar with the
appropriate buttons. This to do list for your toolbars may seem a little intimidating but once
youve done this once or twice it becomes pretty simple. The steps are listed below and well
discuss each item in detail.
1. Define the CSS styles for each button
2. Create the Toolbar
3. Create the Buttons inside the toolbar
4. Reference the CSS styles for each button in HTML
5. Define functionality that will be enabled when button is clicked
6. Create an instance of esri.toolbars.Navigation or esri.toolbars.Draw
7. Connect button events to handler functions
The first thing youll need to do is define the CSS styles for each button that you intend to
include on the toolbar. Each button on your toolbar will need an image, text, or both along
with a width and height for the button. Each of these properties is defined within the CSS.
Next, youll need to use a Dojo Dijit called Toolbar and inside this toolbar youll have one or
more Dijit Buttons, one for each button you intend to include. Each button will need to
reference the corresponding CSS style that you defined in step 1 using the iconClass property.
Finally, youll want to create an instance of either esri.toolbars.Navigation or esri.toolbars.Draw
and connect the button events to a handler function.
In the figure below youll see code examples showing the first five steps for creating a toolbar.
Here we are creating the CSS that defines how each button will appear, constructing the
toolbar and buttons, and referencing the CSS styles for each button via the iconClass property
on each button.

The first code block defines the CSS styles to use for each button. Notice the reference to the
Zoom Out button. As with all the other buttons we define an image to use for the button
(nav_zoomout.png) along with the width and height of the button.
The second code block defines the toolbar and buttons on the toolbar. The toolbar you see in
the example is created using the Toolbar and Button user interface controls provided by Dijit (a
sub-project of Dojo). Each control is enclosed within a <div> tag inside the <body> of the web
page with all buttons being enclosed by the surrounding <div> that contains the Toolbar dijit.
Each button can be assigned both an icon and text. Notice in the figure above that the Zoom
Out Button assigns a value of zoomoutIcon to the iconClass attribute. This simply points to a
CSS style that has been defined at the top of the file. Notice in the example that we have a
style called zoomoutIcon which defines an image to use for our button.
Now that the visual interface for the toolbar and buttons is complete we need to create an
instance of esri.toolbars.Navigation or esri.toolbars.Draw and wire up the events and event
handlers.
Creating an instance of the Navigation class is as easy as calling the constructor and passing in a
reference to esri.map as seen in the code example below. However, youll first want to make
sure that you add a reference to esri.toolbars.navigation.


Finally, we use dojo.connect to wire up an event to an event handler. In this case we are
connecting the onExtentHistoryChange event to the extentHistoryChangeHandler function
which will run when the extent history changes.
In an earlier step we created <div> tags to serve as containers for the toolbar and buttons. The
Navigation class contains a number of constants and methods as seen below.


Each of the buttons that we defined within <div> tags has an onClick attribute which refers to
an event that fires when the button is clicked. In the case of the Zoom Out button seen in the
code example, a click of the button calls the activate method on Navigation. A navigation type
is passed into the activate method. The navigation type can be one of three constants: PAN,
ZOOM_IN, ZOOM_OUT. In each case these buttons are really tools that will require an
additional map action by the user. For example, in the case of ZOOM_IN the user would then
draw a rectangle on the map which would trigger the generation of a new map displayed to the
user.

Weve already discussed the details of creating toolbars and the buttons contained therein.
Hopefully the previous Navigation Toolbar example has illustrated how easy it is to add a
navigation toolbar to your ArcGIS Server application through the JavaScript API. You no longer
have to be concerned with adding in JavaScript code to draw and handle the extent rectangle or
capture mouse coordinates for a pan operation. In addition, the user interface components of
the toolbar can be created easily through various user interface controls supplied by the Dijit
library. The Draw class makes it equally easy to support the drawing of geometries such as
points, lines, and polygons within a similar toolbar. The creation of this toolbar will follow the
same process as we examined with the Navigation toolbar.
Drawing Toolbar
Hopefully the previous section on the Navigation Toolbar has illustrated how easy it is to add a
navigation toolbar to your ArcGIS Server application through the JavaScript API. You no longer
have to be concerned with adding in JavaScript code to draw and handle the extent rectangle or
capture mouse coordinates for a pan operation. In addition, the user interface components of
the toolbar can be created easily through various user interface controls supplied by the Dijit
library.
The Draw class makes it equally easy to support the drawing of geometries such as points, lines,
and polygons within a similar toolbar. The creation of this toolbar will follow the same process
as we examined with the Navigation toolbar.

Creating the Drawing Toolbar
The Drawing toolbar requires the use of the esri.toolbars.draw resource which youd import
into your application through the use of dojo.require().

To create a new instance of the Drawing toolbar simply call the constructor, passing in the map
that it will be associated with.

The toolbar can then be activated with specific mouse behavior for drawing features. The
activate() method on the toolbar accepts a geometry type as well as various options. Only a
single geometry type is passed in to the activate() method each time the toolbar is activated.
Geometry types can include the following:


The code example below illustrates the activation of the drawing toolbar with a freehand
polygon geometry type. This geometry type allows the user to enter a polygon by clicking
multiple points on the map.

Various options can also be supplied as the second parameter in the constructor for the Draw
toolbar. A code example showing various options for the Draw toolbar is shown below. These
include a boolean parameter (showTooltips) that specifies whether or not to show tooltips
when creating new graphics. The tooltip is attached to the mouse as it moves around the
screen. The tooltipOffset option specified how far, in pixels, the tooltip should be offset from
the mouse pointer.


When working with freehand tools such as freehand polygon or freehand line the tolerance
option can be used to define how often a vertice should be placed. Finally, the drawtime option
determines how much time to wait before adding a new point when using a freehand tool. The default
value is 75.

In most cases with the Draw toolbar youll create a number of buttons using Dojo just as was
the case with the Navigation toolbar. A combination of CSS and Dojo dijits can be used to
create these tools.





Chapter 9: Integrating Widgets

The API for JavaScript comes with several out of the box widgets that you can drop into your
application for enhanced productivity. Included are the BasemapGallery, Legend, Scalebar,
OverviewMap, Measure and Bookmarks widgets.
Basemap Gallery Widget
The BasemapGallery widget displays a collection of basemaps from ArcGIS.com and/or a user-
defined set of map or image services. When a basemap is selected from the collection the
current basemap is removed and the newly selected basemap appears. When adding custom
maps to the basemap gallery they will need to have the same spatial reference as the other layers
in the gallery. When using layers from ArcGIS.com this would be the Web Mercator reference
with wkids 102100, 102113, or 3857. It is also recommended that all basemaps be tiled layers
for performance reasons.

When creating a BasemapGallery there are a number of parameters that you can supply in the
constructor including the ability to show ArcGIS basemaps, define one or more custom
basemaps for inclusion in the gallery, supply a Bing maps key, and a reference to the map where
the gallery will be placed. After creating the BasemapGallery widget you need to call the
startup() method to prepare it for user interaction.

Legend Widget
The Legend widget displays a label and symbols for some or all layers in the map. It does have
the ability to respect scale dependencies so that as you zoom in or out in the application the
legend updates to reflect layer visibility at various scale ranges. The Legend widget supports
ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, and FeatureLayer. If using
ArcGIS Server 10.0 SP1 or higher the legend is generated using the REST map service legend
resource. If using ArcGIS Server 10.0 or lower the legend is generated using the ArcGIS.com
legend service.

When creating a new instance of the Legend widget you can specify various parameters that
control the contents and display characteristics of the legend. The arrangement parameter can be
used to specify the alignment of the legend within its container HTML element. The layerInfos
parameter is used to specify a subset of layers to use in the legend, and respectCurrentMapScale
can be set to true to trigger automatic legend updates based on scale ranges for each layer.
Finally, you need to call the startup() method to display the newly created legend.

Scalebar Widget
The Scalebar widget is used to add a scalebar to the map or a specific HTML node. The scalebar
displays units in either english or metric values. You can also control scalebar positioning
through the attachTo parameter. By default, the scalebar is positioned in the bottom left hand
corner of the map.


OverviewMap Widget
The OverviewMap widget is used to display the current extent of the main map within the
context of a larger area. This overview map updates each time the main map extent changes.
The extent of the main map is represented as a rectangle in the overview map. This extent
rectangle can also be dragged to change the extent of the main map. An overview map can be
displayed in a corner of the main map and also hidden from display when not in use. It can also
be placed inside a <div> element outside the main map window or temporarily maximized for
easy access to far away areas of interest.

The OverviewMap widget takes a number of optional parameters in the constructor for the
object. These parameters allow you to control things like where the overview map is placed in
relation to the main map, the base layer to use for the overview map, the fill color for the extent
rectangle, the appearance of a maximize button, and the initial visibility of the overview map.

Measurement Widget
The Measurement widget can be used to measure area and length as well as report the
geographic location of the cursor. Dropping this widget into your application is very simple just
like the other widgets. You can also define custom symbols for the lines and polygons that are
drawn on the screen during the process as well as custom picture symbols for the points.

First, import the resource for the widget.


Then create a new instance of the Measurement object, passing in an option that defines a <div> tag
where the widget should be placed.


Finally, call the startup() method to display the widget.

Bookmarks Widget
The Bookmarks widget allows you to define specific geographic extents for named areas. For
example, in the figure below there are two bookmarks: Northern California and Central
Pennsylvania. When selected from the list the map will reposition the geographic extent to the
extent attached to the bookmark.



To use the Bookmarks widget first import the resource along with a container for the bookmarks.
This is normally a drop-down list or combo list as seen in the figures above.

The individual bookmarks that you add to this widget are defined as an array of JSON objects.
Each bookmark should be given a name, and a geographic extent composed of both a spatial
reference and the coordinates that define the extent.

Finally, create the new Bookmarks object, passing in the variable that references the bookmarks
defined in the JSON object above.

The dojo.byId method is used to reference the <div> container for the bookmark.






Chapter 10: Editing Data
Simple feature editing is supported by the AGIS API for JavaScript when working against data
stored in an enterprise geodatabase format. What this means is that your data needs to be
stored in an enterprise geodatabase managed by ArcSDE. Editing in a web application that uses
the JavaScript API works on the concept of 'last in wins'. For example, if two people are editing
the same feature in a layer, and both submit modifications the last editor to submit changes
will overwrite any changes made by the first editor. Obviously this could pose a problem in
some cases so before implementing editing in your application you will need to examine how
your data could be affected. Other characteristics of editing include support for domains and
subtypes, template style editing, and the ability to edit stand-alone tables and attachments. To
use editing you will need to use a FeatureService and a FeatureLayer. Editing requests are
submitted to the server using an HTTP Post request which in most cases will require the use of
a proxy.
The ArcGIS API for JavaScript provides widgets to make it easier for you to add editing to your
Web applications. The following editing widgets are available.

The API for JavaScript provides several user interface widgets that make it easier to add editing
functionality to your application. These widgets include the Editor, TemplatePicker,
AttributeInspector, and AttachmentEditor. The Editor is the default editing interface and
includes everything you need to edit a layer and also allows you to choose the number and
types of tools available. TemplatePicker displays a pre-configured template containing symbols
for each of the layers in your map document. This template style editing allows your users to
very simply pick a layer and begin editing. The AttributeInspector provides an interface for
editing the attributes of features and ensures valid data entry. Finally, the AttachmentEditor
associates a downloadable file with a feature. We'll examine each of these widgets in more
detail in the coming slides.
What Kind of Editing?
Editing support provided includes feature editing including the creation and deletion of simple
features along with the ability to modify features through moves, cuts, union, or reshaping. In
addition, feature attributes can be edited, documents can be attached to features, and
comments added to features.
Editing Requires a FeatureService
Web editing requires a feature service to provide the symbology and feature geometry of your
data. The feature service is just a map service with the Feature Access capability enabled. This
capability allows the map service to expose feature geometries and their symbols in a way that
is easy for Web applications to use and update.
Before you build a Web editing application, you need to do some work to create a feature
service exposing the layers that you want to be edited. This involves setting up a map
document and, optionally, defining some templates for editing. Templates allow you to pre-
configure the symbology and attributes for some commonly-used feature types. For example,
to prepare for editing streams, you might configure templates for Major Rivers", Minor
Rivers", Streams", and Tributaries". Templates are optional, but they make it easy for the end
user of the application to create common features.
Once your map is finished, you need to publish it to ArcGIS Server with the Feature Access
capability enabled. This creates REST URLs, or endpoints, to both a map service and a feature
service. You will use these URLs to reference the services in your application.
Feature services are accessible in the Web APIs through a FeatureLayer object which we
examined earlier in this module. Feature layers can do a variety of things and can reference
either map services or feature services; However, when you use a feature layer for editing
purposes you need to reference a feature service.
With the editing functionality, your Web application tells the feature layer which attributes
have changed and, if applicable, how the geometry changed. The feature layer also displays the
updated features after editing. You can call the applyEdits() method on the feature layer to
apply the edits, which then commits them to the database.
Editor Widget
The Editor widget provides the default editing interface included with the API. It combines the
functionality of the other widgets to provide everything that you need for editing a layer. You
can choose the number and types of tools that are available on the widget.

The Editor widget saves your edits immediately after they are made. For example, as soon as
you finish drawing a point, it is saved to the database. If you decide not to use the Editor
widget, you must determine when and how often you want to apply edits.
What Tasks Can Editor Widget Perform
The Editor widget provides out-of-the-box editing capabilities using an editable layer in a
Feature Service. It combines the out-of-the-box TemplatePicker, AttachmentEditor,
AttributeInspector and GeometryService to provide feature and attribute editing. When
building editing applications, try to take advantage of the customizable out-of-the-box Editor
widget when possible. This widget allows you to perform all the functions you see listed on this
slide.

To use the Editor widget in your code youll need to first load the widget using dojo.require.
Required parameters for creating a new instance of Editor include a reference to the Map
object and a geometry service.
TemplatePicker Widget
The TemplatePicker displays a pre-configured set of features to the user each symbolizing a
layer in the service. Editing is initiated very simply by selecting a symbol from the template and
then clicking on the map to add features. The symbols displayed in the template come from
editing templates you defined in the feature services source map or symbols defined in the
application. TemplatePicker can also be used as a simple legend.
AttributeInspector Widget
The AttributeInspector provides an interface for editing feature attributes over the Web. It also
ensures that the data they enter is valid by matching the input to the expected data type.
Domains are also supported. For example, if a coded value domain is applied to a field, the
permitted values appear in a drop down list, restricting the possibility of other values being
entered. If a field requires a date value, a calendar appears, helping the user to supply a valid
date.
The Attribute Inspector exposes all available attributes on the layer for editing. If you want to
restrict the available attributes, you must code your own interface for entering and validating
values.
Attachment Editor Widget
In some situations, you may want to associate a downloadable file with a feature. For example,
you might want users to be able to click a feature representing water meter and see a link to an
image of the meter. In the ArcGIS Web APIs, an associated downloadable file like this is known
as a feature attachment.
The AttachmentEditor is a widget that helps users upload and view feature attachments. The
Attachment Editor includes a list of current attachments (with Remove buttons), as well as a
Browse button that can be used to upload more attachments. The Attachment Editor works
well inside an info window, but can be placed elsewhere on the page.
In order to use feature attachments, attachments must be enabled on the source feature class.
You can enable attachments for a feature class in ArcCatalog or the Catalog window in ArcMap.
If the Editor widget detects that attachments are enabled, it will include an Attachment Editor.
Edit Toolbar
There may be times when you dont want to use the default Editor widget. These situations
would include times where you want to code your own editing logic, particularly with regards to
client side display of features and graphics. You can use the Edit toolbar in these cases. The
Edit toolbar is simply a JavaScript helper class that is part of the API. It helps with placing and
moving vertices and graphics. This toolbar is similar to the Navigation and Draw toolbars that
we examined earlier in the class.








Chapter 11: Working with Time Data
New at ArcGIS 10 is the ability to store temporal information as part of a layer. These time-aware layers
store information about the changing state of a dataset over time. By stepping through periods of time
you can reveal patterns and trends in your data that may not have been obvious. Some examples
include the mapping and progression of wildfires, floods, and hurricanes, the visualization of the spread
of disease, and tracking historic demographic patterns. Much like a spatial extent, a Map object built
using the AGIS API for JavaScript can also contain a time extent.
When time aware layers are present in a web application the Map object automatically contains a time
extent. Setting the time extent is similar to setting the spatial extent of a map. Layer information
changes automatically in response to any change in the time extent.
Enabling Time for a Layer
Before your web application can display time-aware data you will need to configure the layers in your
map document that contain time data. This is done in ArcMap. Open the map document file that will
be published as a map service and open the layer properties dialog for the layer(s) you'd like to make
time-aware in your application.

Please note that any layers that you intend to publish as time-aware layers in your web application will
need to contain a field(s) containing date information. Once configured, you then publish your map
document file to ArcGIS Server as a map service. Time aware layers are then referenced from your web
application through either the ArcGISDynamicMapServiceLayer or FeatureLayer class.
Working with Time-Aware Layers in JavaScript API
There are two ways to work with time-aware layers in your AGIS API for JavaScript web application. You
can use the TimeSlider widget which is a user interface component that handles updating the maps time
extent. This widget contains a reference bar, thumbs, and controls for starting and stopping the
component. You can also work with time-aware layers through the Web API to perform temporal
queries, filter layers using time definitions, and to set the maps time extent.
The Time Slider Widget
The TimeSlider widget simplifies the process of visualizing temporal data through a user interface
component. TimeSlider has a number of elements that you need to understand before using it in your
applications. Each widget can contain one or two thumbs. As a general rule, using one thumb displays
either data at a point in time or cumulative data up to a point in time. Two thumbs are used to display
data within a time range. In addition to thumbs, the TimeSlider also contains controls for starting and
stopping the progression of time, manually advancing the thumb(s), and stepping back in time. Finally,
tic marks represent specific dates along the timeline. The TimeSlider widget is represented in the API by
a TimeSlider class which can also be used to filter the map display to show cumulative data to a point in
time, a single point in time, or data that falls within a time range.




A TimeSlider is added to your web application through the TimeSlider class in the API. The process of
adding a TimeSlider requires six steps.

Add time aware map or feature service to Map
1. Use ArcGISDynamicMapService or FeatureLayer
2. Create TimeSlider instance
3. Associate time slider with map
4. Define thumbs, time slice, tics
5. Define time slice to visualize
6. Call startup() method




TimeSlider Properties
There are a number of properties on TimeSlider that you should be aware of. TimeSlider.loop is a
boolean value that controls continuous looping. TimeSlider.thumbCount defaults to 1 and controls how
many thumbs appear on the slider. You can control the speed at which the thumb advances through the
TimeSlider.thumbMovingRate property which by default is set to 1000 milliseconds or 1 second. You
can change this value to speed up or slow down the advancement. Finally, TimeSlider.timeStops is an
array of dates. Each date represents one tic mark that will appear on the slider.
Filtering Time Data
Data for time aware layers can be filtered in a couple different ways. The Map.setTimeExtent() method
filters by a specific input time. You can also apply a time definition to Feature Layers. This limits the
data loaded to the initial query and is similar to setting a definition expression with the difference being
that features are only displayed if they match the input time extent. In the code example you see on
this slide, only features between the start and end date will be displayed.






Chapter 12: Spatial and Attribute Queries
In this chapter we will discuss the many types of tasks that can be performed with the ArcGIS
Server API for JavaScript. Tasks give you the ability to perform spatial and attribute queries,
find features based on text searches, geocode addresses, identify features, and perform various
geometry operations including buffering and distance measurements. All tasks are accessed
through the esri.tasks resource which can be specified through dojo.require( ).
All tasks in the ArcGIS Server API for JavaScript follow the same pattern. This pattern is easily
recognizable once youve worked with one or more tasks for any length of time. A diagram of
this task process is provided below. An input object is used to supply input parameters to the
task. Using these input parameters, the task performs a specific function and then an output
object is returned containing the results of the task. The first task well examine is QueryTask.
Notice the pattern of this task object as you work through the materials. This same basic pattern
will be repeated with all the task objects that we cover in the next few chapters.

Performing Spatial and Attribute Queries with Query Task
With the ArcGIS Server Query Task you can perform attribute and spatial queries against data
layers in a map service that have been exposed. You can also combine these query types to
perform a combination attribute and spatial query. Some examples would perhaps be illustrative
at this point. An attribute query might search for all land parcels with a valuation of greater than
$100,000. A spatial query could be used to find all land parcels that intersect a 100 year
floodplain, and a combination query might search for all land parcels with a valuation of greater
than $100,000 and whose geometry intersects the 100 year floodplain.
As youll see with most tasks, queries are performed using a sequence of objects that typically
include input to the tasks, execution of the tasks, and a result set returned from the operation.

Query Class
The input for your query is stored in a Query object (see figure below) which contains various
parameters that can be set for the query. At least one of the following properties must be set:
geometry, text, or where. Commonly used optional properties include outFields,
outSpatialReference, and returnGeometry.
In the code example you see below, the text property has been set along with outfields and
returnGeometry. The text and where properties are used to define an attribute query while the
geometry and spatialRelationship properties in combination define a spatial query. Setting the
returnGeometry property to false indicates that we do not want ArcGIS Server to return
features that matched the query. Only the tabular data will be returned in this case. This would
be typical for an application that wants to display the results in a non-map component such as a
grid. The outfields property is an array of attribute fields that should be returned in the results.
Field names should be enclosed by double quotes and separated by commas. The fields must
actually exist in the layer and must be defined by the actual field names rather than a field alias.
You should get into the habit of setting this property to limit the fields to only those you expect
to use in the results. Performance of your application will be improved since it avoids the
performance hit of having to return fields of information that will not be used.

The QueryTask object executes the task using the input provided in the Query object, and the
result set is stored in a FeatureSet object which contains an array of Graphic features.


A Query object is used as input to a QueryTask and is defined by properties such as geometry,
where, and text. The geometry property is used to input a geometry that will be used in a spatial
query and will be a point, line, or polygon geometry. The where property is used to define an
attribute query, and the text property is used to perform a where clause containing a like
modifier. The Query object can also contain a number of optional properties including the
ability to define the fields that will be returned as a result of the query (outfields), the output
spatial reference for the return geometry (outputSpatialReference), and the actual geometry of
the features that meet the query conditions.


Once youve defined the input properties in a Query object you can then use QueryTask to
execute the query on a layer. Notice in the code example below that we first create a new
variable called myQueryTask which points to layer 6 in the ESRI_CENSUS_USA map service.
We then create the Query object containing the input properties of the query and finally we use
the execute( ) method on QueryTask to perform the query. Execute returns a FeatureSet object
that contains the results of the query and these features are processed through a callback function
called showResults which is specified in the execute( ) method.



As I mentioned, the results of a query are stored in a FeatureSet object which is simply an array
of Feature graphics which you can then plot on your map if you wish. Each feature in the array
can contain geometry, attributes, symbology, and an InfoTemplate. Typically these features are
plotted on the map as graphics.

Now that you understand the basic concepts of performing a query using a QueryTask well take
a look at some specific examples.

Performing Spatial Queries
Spatial queries, such as finding parcels of land that intersect a 100-year floodplain can be
accomplished through QueryTask by setting the geometry and optionally the
spatialRelationship properties on the Query object. The geometry property defines a geometry
to use as the spatial filter. Valid geometry types include Extent, Point, Multipoint, Polyline, or
Polygon. The spatial relationship as specified by spatialRelationship is applied to the geometry
while performing the query. One of the valid constants seen below that defines the type of
spatial relationship needs to be supplied.
SPATIAL_REL_CONTAINS Part or all of a feature from feature class 1 is
contained within a feature from feature class
2.
SPATIAL_REL_CROSSES The feature from feature class 1 crosses a
feature from feature class 2.
SPATIAL_REL_ENVELOPEINTERSECTS The envelope of feature class 1 intersects
with the envelope of feature class 2.
SPATIAL_REL_INDEXINTERSECTS The envelope of the query feature class
intersects the index entry for the target
feature class.
SPATIAL_REL_INTERSECTS Part of a feature from feature class 1 is
contained in a feature from feature class 2.
SPATIAL_REL_OVERLAPS Features from feature class 1 overlap
features in feature class 2.
SPATIAL_REL_RELATION Allows specification of any relationship
defined using the Shape Comparison
Language.
SPATIAL_REL_TOUCHES The feature from feature class 1 touches the
border of a feature from feature class 2.
SPATIAL_REL_WITHIN The feature from feature class 1 is
completely enclosed by the feature from
feature class 2

The code example below details this procedure.

Performing Attribute Queries
Attribute queries can be performed against layers and tables exposed by an ArcGIS Server
instance. The where and text properties are used to define attribute queries. Any legal SQL
where clause can be used in the where property. Similarly, the text property defines a where
clause as a like statement. However, the field used to perform the query is the display field
defined in the map document (mxd). You can also consult the Services Directory for the layer
you are querying to determine the display field.

Combining Spatial and Attribute Queries
Spatial and attribute queries can easily be combined simply by including the relevant properties
for each type of query.

Chapter 13: Obtaining Feature Information

Identifying features is another common operation found in any GIS application. This common
operation typically requires a click on the map and then the application returns the attributes of
features that have been clicked on a map.

This functionality is accomplished through the API with the IdentifyTask class. As with the
other task processes the IdentifyTask object uses an input parameters object. This input object,
called IdentifyParameters, contains various parameters that control the results of an identify
operation. A number of properties can be set for your identify operation with the
IdentifyParameters object. Parameters include the geometry used to select features, the layer ids
on which to perform an identify, and the tolerance from the specified geometry within which the
identify should be performed. An identify can be performed on individual layers, the top most
layer in a service, all visible layers in a service, or all layers in a service.



IdentifyTask performs the identify operation on one or more layers using the parameters
specified in IdentifyParameters. As with the other tasks that weve examined, IdentifyTask
needs a pointer to a URL that identifies the map service to use for the identify operation.



The results of an identify operation performed with IdentifyTask are stored in an instance of
IdentifyResult. This object contains the feature returned from the operation along with the layer
id and layer name where the feature was found.


Chapter 14: Finding Features

Tasks that you can execute with the ArcGIS Server API for JavaScript are some of the most
commonly used functions in ArcGIS Desktop, and the Find features task is a commonly used
function in ArcGIS Desktop. Just as in the desktop version of ArcGIS, this task can be used to
find features in a layer that match a string value. Before executing a find operation with a
FindTask object you will need to set various parameters of the operation in an instance of
FindParameters.
FindParameters gives you the ability to set various options including the search text, fields to
search and others. Using the FindParameters object, FindTask then executes its tasks against
one or more layers and fields and returns a FindResult object that contains the layerID,
layerName, and feature that matched the search string.

FindParameters is used to specify the search criteria for a find operation and includes a
searchText property that includes the text that will be searched for along with properties that
specify the fields and layers that will be searched. In addition, setting the returnGeometry
property to true indicates that you want to return the geometry of the features that matched
the find operation, and can be used to highlight the results.


FindTask executes a find operation against the layers and fields specified in FindParameters and
returns a FindResult object that contains the objects that were found. Just as with QueryTask
and IdentifyTask, you must specify a URL pointer to the map service that will be used in the find
operation, but notice that you do not need to include an integer value specifying the exact data
layer to use. This is not necessary because the layers and fields to be used in the find operation
were defined in the FindParameters object. A callback function is used to process the results
stored in an instance of FindResult.


FindResults contains the results of a FindTask operation and contains features that can be
represented as graphics, layer ids and names where the feature was found, and the field name
containing the search string.


Chapter 15: Turning Addresses into Points with Geocoding

In ArcGIS Server, a Locator task performs geocoding and reverse geocoding. Geocoding is the
process of assigning a coordinate to an address while reverse geocoding assigns an address to a
coordinate. The figure below illustrates this process. An address, defined by an object in
JavaScript, is input to a Locator object which geocodes the address and returns the results in an
AddressCandidate object which can then be displayed as a point with a SimpleMarkerSymbol
on your map.

A Locator service can accept either a point or an object. An object is simply a generic term that
indicates an address that is formatted in the form of an object as seen in the code example
below. The address is defined as a series of name/value pairs defined within brackets.
Individual name/value pairs are defined for the street, city, state, and zipcode in this case, but
the name/value pairs will vary depending upon the type of geocoding service youve defined in
your locator. For reverse geocoding the input to a Locator takes the form of a
esri.geometry.point object which is often defined through a user click on the map or perhaps
through application logic.

The Locator class contains methods and events that can be used to execute a geocode or
reverse geocode operation using the input point or address object. Locator needs a URL
pointer to your geocoding service as defined within ArcGIS Server. Once a new instance of a
Locator has been created you can call the addressToLocations( ) method to geocode an address
or the locationToAddress( ) method to perform a reverse geocode. These methods result in an
event that is fired at the completion of the operation. In the case of an address geocode, the
onAddressToLocationsComplete( ) event fires, and the onLocationToAddressComplete( ) event
fires at the completion of a reverse geocode operation. In either case, an AddressCandidate
object is then returned to the event.

An AddressCandidate object is returned as a result of a Locator operation. Various properties
are stored in this object including the address, attributes, location, and score. The attributes
property contains name/value pairs of field names and values. The location is as the name
would suggest the x,y coordinate of the candidate address, and the score property is a numeric
value between 0-100 that indicates the quality of address returned with a higher score
representing a better match. Multiple addresses can be stored in this object as an array of
candidates.

Lets take a little closer look at the Locator methods used to submit addresses and points. The
Locator.addressToLocations method sends a request to geocode a single address. As you can
see from the figure below, an input address object is created and used as a parameter in the
addressToLocations method found on a Locator object. The results of the geocoding operation
are returned in an AddressCandidate object. The address can then be plotted on the map as a
graphic.

Reverse geocoding can also be performed by a Locator object through the locationToAddress
method. A point object, created either by an end user click on the map or through application
logic, is created and passed as a parameter into the locationToAddress method. A second
parameter is also passed into the method indicating a distance in meters from the point within
which a matching address should be searched. As with the addressToLocations method, an
AddressCandidate object is returned from the locator and contains an address if one was found.


Chapter 16: Network Analysis Functions
Routing
Routing in the API for JavaScript allows you to use the RouteTask to find routes between two or more
locations and optionally get driving directions. The RouteTask uses network analysis services to
calculate the routes and can include both simple and complex routes that include multiple stops,
barriers, and time windows. RouteTask uses a least-cost path between multiple locations in a network.
Impedence on the network can include time and distance variables.

As with the other tasks we have examined in this class, routing is accomplished through a series of
objects including RouteParameters, RouteTask, and RouteResult. RouteParameters provides the input
parameters to RouteTask which submits a routing request to ArcGIS Server using the input parameters.
Results are returned from ArcGIS Server in the form of a RouteResult object.

RouteParameters
RouteParameters serve as input to the RouteTask object and can include stop and barrier locations,
impedance, whether or not to return driving directions and routes, and many others. You can obtain a
full list of all the parameters at the link provided. A brief code example is also provided showing how to
create an instance of RouteParameters, add stops and define the output spatial reference.
RouteTask
RouteTask executes a routing operation using input parameters supplied by RouteParameters. The
constructor for RouteTask takes a pointer to a URL that identifies the network service to use for the
analysis. Calling the solve() method on RouteTask executes a routing task against the network analysis
service using the input parameters supplied.
RouteResults
A RouteResult object is returned from the network analysis service to a callback function provided by
RouteTask. The callback function then handles the data by displaying it to the user. The data returned
is largely dependent upon the input supplied to the RouteParameters object. For instance, directions
are returned only if RouteParameters.returnDirections is set to true. Data returned can include
directions, the route between points, the route name, and an array of stops.
Closest Facility Task
A new task added to the ArcGIS API for JavaScript is the ClosestFacility task. The closest facility solver
measures the cost of traveling between incidents and facilities and determines which are nearest to one
other. When finding closest facilities, you can specify how many to find and whether the direction of
travel is toward or away from them. The closest facility solver displays the best routes between
incidents and facilities, reports their travel costs, and returns driving directions.

The AGIS API for JavaScript classes involved in solving closest facility operations include
ClosestFacilityParameters, ClosestFacilityTask, and ClosestFacilitySolveResults.
ClosestFacillityParameters includes input parameters such as the default cutoff, whether or not to
return incidents, routes, and directions, and more. These parameters are used as input to the
ClosestFacilityTask which calls the solve() method passing in the parameters. Finally, results are passed
from ArcGIS Server back to the client in the form of a ClosestFacilitySolveResults object.

ClosestFacilityParameters
The ClosestFacilityParameters object is used as input to ClosestFacilityTask. Some of the more
commonly used properties on this object are presented below. The incidents and facilities properties
are used to set the locations for the analysis. The data returned by the task can be controlled through
the returnIncidents, returnRoutes, and returnDirections properties which are simply true/false
values indicating whether the information should be returned in the results. The travelDirection
parameter specifies whether travel should be to or from the facility and defaultCutoff is the cutoff
value beyond which the analysis will stop traversing.
ClosestFacilityTask
The ClosestFacilityTask accepts the input parameters provided by ClosestFacilityParameters and submits
them to a network analysis service using the solve() method. When you create a new instance of
ClosestFacilityTask you will need to point to a REST resource representing a network analysis service.
ClosestFacilitySolveResult
The result object returned from a ClosestFacilityTask operation is a ClosestFacilitySolveResult. This
object can contain various properties including a DirectionsFeatureSet which is an array of directions.
This DirectionsFeatureSet object contains the turn by turn directions text and geometry of the route.
The attributes for each feature provide information associated with the corresponding route segment.
Attributes returned include the direction text, length of route segment, time to travel along the route
segment, and estimated time of arrival at the route segment. Other properties contained within
ClosestFacilitySolveResults including arrays containing the facilities and incidents, an array of polylines
representing the routes returned, any messages returned, and arrays containing barriers.
Service Area Task
The new Service Area task calculates the service area around an input location. This service area is
defined in minutes and is a region that encompasses all accessible streets within that time range.

The AGIS API for JavaScript classes involved in service area operations include ServiceAreaParameters,
ServiceAreaTask, and ServiceAreaSolveResults. ServiceAreaParameters includes input parameters such
as the default break, facilities involved, barriers and restrictions, travel direction, and more. These
parameters are used as input to the SerivceAreaTask which calls the solve() method passing in the
parameters. Finally, results are passed from ArcGIS Server back to the client in the form of a
ServiceAreaSolveResults object.

ServiceAreaParameters
The ServiceAreaParameters object is used as input to ServiceAreaTask. The defaultBreaks property is
an array of numbers defining the service area. For instance a single value of 2 can be provided to
indicate that wed like to return a 2 minutes service area around the facility. The returnFacilities
property, when set to true, indicates that the facilities should be returned with the results. Various
point, polyline and polygon barriers can be set as well through the barriers properties. Travel direction
for the analysis can be to or from the facility and is set with the travelDirection property. There are
many other properties that can be set on ServiceAreaParameters. Please see the API documentation for
details.
ServiceAreaTask
ServiceAreaTask finds service areas around a location using a street network. The constructor for
ServiceAreaTask should point to a REST resource representing a network analysis service. To submit a
request to solve a service area task you will need to call the solve() method on ServiceAreaTask.
ServiceAreaSolveResult
The result object returned from a ServiceAreaTask operation is a ServiceAreaSolveResult. This object
can contain various properties including a ServiceAreaPolygons property which is an array of service
area polygons returned from the analysis. In addition, other properties include facilities, messages, and
barriers.








Chapter 17: Geometry Tasks

A GeometryService is used to perform various geometric operations including buffering of
features, simplification of a geometry, projection to a new spatial reference, and the calculation
of length and area. Each geometric operation fires a corresponding event upon completion and
a graphic object is passed into this event. For example, when a buffer operation completes, the
onBufferComplete(graphic) event is fired.
Buffering features is one of the more common functions in a GIS, and the ArcGIS Server API for
JavaScript provides this capability through the GeometryService. The GeoemtryService.buffer( )
method accepts buffer parameters as an input and returns an output containing an array of
graphic polygons which can then be plotted on your map.


Buffering Features
Before a feature can be buffered you need to set various properties through the
BufferParameters object. Properties include distances and units of measure. The distance
property allows you to set multiple distances for your buffer operations using an array of
numeric values. This is handy for creating multi-buffer polygons of various distances. The units
property also needs to be set and can be set to feet, meters, kilometers, and miles. Other
important parameters include features property which specifies the input feature to be
buffered. UnionResults is a true/false value that indicates whether you should union all buffers
into a single output polygon. Finally, the outSpatialReference property is used to specify an
output spatial reference for the returned graphics.

The buffer( ) method on GeometryService is used to perform the buffer using input parameters
specified in a BufferParameters object. As you can see from the code example on this slide,
when a new instance of a GeometryService is created you need to point to a URL containing a
valid map service. A callback function is executed upon return from the buffer( ) method and
an array of graphic polygons is passed into the callback function for processing.

Calculating Areas and Lengths
Calculation of areas and lengths of polygons and polylines can be accomplished through two
methods on GeometryService. The areasAndLengths( ) method can be used against polygons
while the lengths( ) method is used against polylines. Both methods accept an array of
Graphics as input and return length and area objects as numeric arrays.

Data Projection
The GeometryService also provides the capability of projecting your data to a new spatial
reference through the project( ) method. This method accepts an array of graphics as input
along with an output spatial reference specified in well known id format or WKID. The full list
of projected and geographic coordinate systems WKIDS can be found at the link found on this
slide. An array of graphics containing the newly projected data is returned.

Chapter 18: Using the Geoprocessor
Geoprocessing refers to the automation and chaining of GIS operations in a logical fashion to
accomplish some sort of GIS task. For example, you may want to buffer a stream layer and then
clip a vegetation layer to this newly created buffer.
A model, like the one that you see below, can be built in ArcGIS Desktop using ModelBuilder.
Models are run in an automated fashion from either a desktop environment or via a centralized
server accessed through a web application.

Any tool found in ArcToolbox whether that be a tool for your ArcGIS license level or a custom
tool that youve built can be used in a model and chained together with other tools. Once
constructed, these models can be run on a centralized server and accessed via web applications.
In this section we will examine how you can access these geoprocessing tasks through the
ArcGIS Server API for JavaScript.
What is a Geoprocessing Task?
Models are built in ArcGIS Desktop using ModelBuilder. Once built these models are published
to ArcGIS Server as geoprocessing tasks. Web applications then use the Geoprocessor object
found in the ArcGIS Server API for JavaScript to access these tasks and retrieve information.
These models and tools are run on ArcGIS Server due to their computationally intensive nature
and need for ArcGIS software.
Jobs are submitted to the server through a web application and the results are picked up after the
service has completed. Submitting jobs and retrieving the results can be accomplished through
the Geoprocessor object.
This process is illustrated in the figure below.


Obtaining Information about a Geoprocessing Task
There are three things that you need to know when using a geoprocessing service. First, you
need to know the URL where the model or tool is located. An example URL is provided below:

http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Population_W
orld/GPServer/PopulationSummary

When you go to this link you can also find information about the input and output parameters,
whether the task is asynchronous or synchronous and much more. Speaking of input and output
parameters, you must know the datatypes associated with those parameters, and whether or not
each of the parameters is required. Finally, you need to know whether the task is asynchronous
or synchronous and how your code should be configured based on that knowledge.

Input Parameters
There are a number of details that you must remember regarding input parameters that are
submitted to the geoprocessing task. Almost all geoprocessing tasks will require one or more
parameters. These parameters can be either required or optional and are created as JSON
objects. When creating parameters as JSON objects you must remember to create them in the
exact order that they appear on the services page. The parameter names must also be named
exactly as they are on the services page.

Below you will see an illustration of the input parameters supplied to a geoprocessing task.
When coding your JSON input parameters object it is critical that you provide the exact
parameter name as given on the services page and that you provide the parameters in the order
that they appear on the page. Notice in our code example that we are providing two parameters:
Input_Observation_Point and Viewshed_Distance. Both parameters are required and we have
named them exactly as they appear on the services page and they are in the correct order.

The Geoprocessor
The Geoprocessor class in the ArcGIS Server API for JavaScript represents a GP Task resource
which is a single task in a geoprocessing service. Input parameters are passed into the
Geoprocessor through a call to either Geoprocessor.execute() or Geoprocessor.submitJob. We'll
discuss the difference between these two calls in more detail soon. After executing the
geoprocessing task the results are returned to the Geoprocessor object where they are processed
by a callback function.
Creating an instance of the Geoprocessor class simply requires that you pass in the url that points
to the geoprocessing service exposed by ArcGIS Server. It does require that you import
esri.tasks.gp.
Running the Task
Once you have an understanding of the geoprocessing models and tools available to you for an
ArcGIS Server instance as well as the input and output parameters you can begin writing the
code that will execute the task. Geoprocessing jobs are submitted to ArcGIS Server for either
synchronous or asynchronous execution. A synchronous execution implies that the client calls
for execution of the task and then waits for the result before continuing with the application
code. In asynchronous execution a client submits a job, continues to run other functions, and
checks back later for completion of the job. By default, the client checks back for completion
every second until the job has finished. The Services page tells you how to submit your job for
each geoprocessing task. Simply look for Execution Type on this page.

Synchronous tasks require that your application code submit a job and wait for a response before
continuing. You will need to use the Geoprocessor.execute( ) method with the property input
parameters and callback function supplied. The callback function is executed when the
geoprocessing task returns the results of the job that was submitted. These results are stored in
an array of ParameterValue.
Asynchronous tasks require that you submit a job, continue working on other functions while
waiting for the process to finish, and then checking back in with ArcGIS Server on a periodic
basis to retrieve the results after completion. The Geoprocessor.submitJob( ) method is used to
submit a job to the geoprocessing task. You will need to supply input parameters, a callback
function, and a status callback function. The status callback function executes each time your
application checks back for the results. By default, the status is checked once per second.
However, this interval can be changed using the Geoprocessor.setUpdateDelay( ) method. Each
time the status is checked, a JobInfo object is returned and contains information indicating the
status of the job. When JobInfo.jobStatus is set to STATUS_SUCCEEDED, the complete
callback function is then called.
A visual diagram (seen below) of the process flow that occurs on asynchronous tasks can help to
reinforce how these types of tasks operate. Input parameters are created and input to the
geoprocessor object which uses these parameters to submit a geoprocessing job to ArcGIS
Server. The Geoprocessor object then executes the statusCallback function at regular intervals.
This function checks with the geoprocessing service to see if the job has finished. A JobInfo
object is returned and contains a status indicator indicating its completion status. This process
continues until the job completes at which time a completeCallback function is called and passed
the results of the job.




Chapter 19: Integration with ArcGIS.com
ArcGIS.com is a Web site for working with maps and other types of geographic information.
Visit the site to create maps; find and use maps, applications, and tools; and share your maps and
applications with others. Within the site, you will find applications for building and sharing
maps. You will also find useful basemaps, data, applications, and tools that you can view and
use, plus communities you can join. For custom web mapping application developers the really
exciting news is that you can integrate ArcGIS.com content into your custom developed
applications using the ArcGIS Server API for JavaScript.

The ArcGIS Server API for JavaScript includes a couple utility methods for working with maps
from ArcGIS.com. Both methods are found on the esri.arcgis.utils resource. The createMap()
method is used to create a map from an ArcGIS.com item.
The WebMap ID
Each map in the ArcGIS.com gallery has a unique ID. This unique ID, called webmap will be
important when you begin creating custom applications that integrate maps from ArcGIS.com.
To get the webmap ID for a map that youd like to add to your JavaScript API application
simply click a map that youve found which has been shared in ArcGIS.com. The address bar
will contain the webmap ID for the map. Youll want to make note of this ID.

Once you have obtained the webmap ID for the ArcGIS.com map that youd like to integrate
into your custom JavaScript API application youll need to call the getItem() method, passing in
the webmap ID. The getItem() method returns a dojo.Deferred object. Dojo.Deferred is an
object built specifically for tasks that may not complete immediately. It allows you define
success and failure callback functions that will execute when the task does complete. In this
case, a successful completion will pass in an itemInfo object to the success function. This
itemInfo object will be used to create the map from ArcGIS.com inside your custom
application.
Code Example
Well cover this entire function in two separate examples. For now well examine the use of the
getItem() method along with setting up callback functions for success or failure. In the first line
of code we create a variable called agoId and assign it the webmap ID that wed like to use.
Next we call getItem(), passing in the agoId variable containing our webmap ID. This creates
a new dojo.Deferred object which we assign to a variable called itemDeferred. Using this
object we can then create success and error callback functions. The success function, called
addCallback is passed an itemInfo object that well use to create our map. Well cover the
actual creation of the map next. In the event of some type of error condition, the addErrback
function would be called. Now lets see how the map is created.

The createMap() method is used to actually create the map from ArcGIS.com. This method
takes an instance of itemInfo which is returned from a successful call to getItem() or you can
simply provide the webmap ID. As with any map that you create with the ArcGIS Server API
for JavaScript you also need to provide a reference to a <div> container that will hold the map
and any optional map options that youd like to provide. Just as with the getItem(), createMap()
also returns a dojo.Deferred object that you can use to assign success and error callback
functions.
In the second half of this code example we start by calling the createMap() function and passing
in an instance of 'itemInfo' along with the container <div> to hold the map and map options for a
slider and geometry service. The result of createMap() is a new dojo.Deferred object which we
assign to the variable 'mapDeferred'. With this object we can define success and error callback
functions. The success function accepts a 'response' object which contains a 'map' property that
we use to retrieve the actual map. The error function runs when a error occurs that would
prevent the creation of the map.

You might also like