GIS Tutorial – ArcGIS Server API for JavaScrip

download GIS Tutorial – ArcGIS Server API for JavaScrip

of 138

Transcript of GIS Tutorial – ArcGIS Server API for JavaScrip

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    1/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 Serverresources 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,

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    2/138

    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 bepublished 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    3/138

    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 ortraditional 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 casesthese 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    4/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    5/138

    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 SOMcoordinates 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 andtesting purposes, as well as small deployments.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    6/138

    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 sinceediting 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    7/138

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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    8/138

    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 ispreferable 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 referto ourBuilding 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.

    http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    9/138

    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 greatlysimplifies 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 asBorderContainer. 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 differentregions: 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%.

    http://docs.dojocampus.org/dijit/layout/BorderContainerhttp://docs.dojocampus.org/dijit/layout/BorderContainerhttp://docs.dojocampus.org/dijit/layout/BorderContainerhttp://docs.dojocampus.org/dijit/layout/BorderContainer
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    10/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    11/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    12/138

    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 theArcGIS API for JavaScript Samplesand 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.

    http://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htmhttp://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htmhttp://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htmhttp://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htmhttp://help.arcgis.com/en/webapi/javascript/arcgis/help/jssamples_start.htm
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    13/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    14/138

    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 alongwith 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    15/138

    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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    16/138

    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: declarativelyby using special attributes inside of regular

    HTML tags, and programmaticallythrough 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    17/138

    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 section of your HTML page you will need to include references to theArcGIS 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 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 or a 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 throughDijits.

    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 yourapplication. 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 shou ld be

    placed inside the section of your web page.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    18/138

    After including the boilerplate code that references the ArcGIS Server JavaScript and Dojo

    APIs along with the style sheet informationand 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 ourBuilding 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

    http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    19/138

    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 coverthese 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 thenecessary 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 , , ,

    , and .

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    20/138

    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 , , and tags.The 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

    tag. For instance, your mapping applications will contain a tag inside the 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

    tags and within a 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 section. Well explore this topic later. For now justconcentrate on placing your code inside the tags.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    21/138

    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 HTMLcode by URI, file upload, or direct input.

    http://validator.w3.org/http://validator.w3.org/http://validator.w3.org/http://validator.w3.org/
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    22/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    23/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    24/138

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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    25/138

    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

    alsoperfectly 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;

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    26/138

    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. Forinstance, 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    27/138

    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 section of a web page inside

    a tag, but can also be defined in the section. However, in most cases you will

    want your functions defined within the 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 complexstructures 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 ho ld

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    28/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    29/138

    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 inHTML 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    30/138

    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 tag that will serve as the container for the map you define an id and assignit 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    31/138

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    32/138

    Figure 18: Map Border Styling

    Unlike id selectors which are used to assign styles to a single element, class selectors are usedto 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 tag. This is a commonly

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    33/138

    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 tag and enclosed inside a 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 fourthlevel 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 , 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    34/138

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

    http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100http://www.geospatialtraining.com/index.php?option=com_catalog&view=node&id=37%3Abuilding-custom-arcgis-server-applications-with-javascript&Itemid=100
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    35/138

    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 mostfundamental 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 files2. Create a container for the map3. Create an initialization script that performs initial setup operations4. 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 tag as you can see

    in the code example below. Please note that you can place all the text you see in this code

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    36/138

    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 tag.

    Any tags need to be defined inside the 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 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/.

    http://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.htmlhttp://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.htmlhttp://archive.dojotoolkit.org/nightly/dojotoolkit/dijit/themes/themeTester.html
  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    37/138

    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 tag which acts as a container for the map. The tag needs to be

    placed somewhere inside the tag. Please also note that you need to use the IDattribute 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

    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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    38/138

    performs any other startup routines. You will use the ID that you assigned to your tag in

    this step to place the newly created map inside the 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 tag.

    Inside this 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 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 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 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    39/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    40/138

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

    below.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    41/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    42/138

    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 youcan 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 ) and the options specify one or more optional parameters such as

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    43/138

    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 ID is a required parameter for the constructor and is used to specify the container forthe 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 tag that will serve as the container for

    your map. This is done by passing in the ID of the 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 closerlook 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    44/138

    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 optionsthat you can set including:

    layerThe base layer used to initialize the map navTrue/False value indicating whether to display pan buttons on the map displayGraphicsOnPanTrue/False value indicating whether graphics should be

    displayed during panning.

    sliderTrue/False value indicating if the zoom slider should be displayedThe Spatial Reference

    The MXD or MSD used to create a map service defines the spatial reference that will be usedfor 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 youadd 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    45/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    46/138

    Figure 23: Dynamic Map Service Layers

    Tiled map service layers (see Figure X) reference a pre-defined cache of map tiles instead ofdynamically 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    47/138

    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 Xyoucan 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 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 meaningthat you cant specifically create an object from these classes in your application.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    48/138

    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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    49/138

    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 theMap.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 BingMaps 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    50/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    51/138

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

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    52/138

    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.setExtentmethod 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    53/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    54/138

    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 besomething 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 NavigationMap 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 tobe 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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    55/138

    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.

  • 8/21/2019 GIS Tutorial ArcGIS Server API for JavaScrip

    56/138

    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 us