Building Web and Mobile ArcGIS Server Applications with JavaScript

4.8 (5 reviews total)
By Eric Pimpler
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introduction to HTML, CSS, and JavaScript

About this book

ArcGIS Server is the leading software for developing both web and mobile GIS applications. There are a number of programming languages that you can use to develop applications with ArcGIS Server including JavaScript, Flex, and Silverlight. However, the ArcGIS API for JavaScript is the preferred way of developing your custom applications for ArcGIS Server since it can be used for both web and mobile application development. It’s easy to use and doesn’t require the use of a browser plugin.

This tutorial-based guide provides you with hands-on experience in developing custom web and mobile ArcGIS Server applications with step-by-step style exercises. Along with introducing you to the HTML/CSS/JavaScript technology stack, you will learn to add intuitive geographic layers of information to your map, interactive query and display of spatial data, add user interface widgets, access geoprocessing tasks, and many more in your own web and mobile GIS applications.

With this practical, hands-on guide, you will be able to develop fully-functional online GIS applications with ArcGIS Server using the ArcGIS API for JavaScript. After creating your own map, you will explore how to add geographic layers from a variety of sources including tiled and dynamic map services, add graphics to the map, and stream geographic features to the browser using a FeatureLayer.

Most applications include the specific functionalities implemented by ArcGIS Server as tasks. You’ll learn how to use the various tasks provided by ArcGIS Server including spatial and attribute queries, identification of features, finding features by attribute, and more. Geocoding and geoprocessing tasks are covered in-depth to help you accomplish your task in GIS. Finally, you’ll learn just how easy it is to integrate ArcGIS.com content into your custom developed applications.

This comprehensive guide quickly advances through probing programmatic techniques for building web and mobile GIS applications which will make application development a lot easier!

Publication date:
February 2014
Publisher
Packt
Pages
274
ISBN
9781849697965

 

Chapter 1. Introduction to HTML, CSS, and JavaScript

There are certain fundamental concepts that you need to understand before you can get started with developing GIS applications with the ArcGIS 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 you're new to any of these concepts, read on. We are going to cover these topics at a very basic level, just enough to get you started. For a more advanced treatment on any of these subjects, there are many learning resources available, including books and online tutorials. You can refer to Appendix, Application Design with ArcGIS Templates and Dojo, for a more comprehensive list of these resources.

In this chapter, we will cover the following topics:

  • Basic HTML page concepts

  • JavaScript fundamentals

  • Basic CSS principles

 

Basic HTML page concepts


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 you're developing applications with the ArcGIS API for JavaScript. The code you write will be placed inside an HTML page or a JavaScript file. HTML files typically have an .html or .htm file extension and JavaScript files have a .js extension. Once you have created a basic HTML page, you can go through the steps required to create a basic map with the ArcGIS 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 HTML tags.

The following 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>. Use your favorite text or web editor to enter the following code. I use Notepad++ but there are many other good editors available. Save this example as helloworld.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Topographic Map</title>

  </head>
  <body>
      Hello World
  </body>
</html>

There are a different types of HTML currently in use. The new HTML5 is getting a lot of press and you'll likely see this implementation being used almost exclusively for the development of new applications; so, we'll focus on HTML5 throughout the book. However, I do want to make you aware that there are other flavors of HTML in use, the most common being HTML 4.01 (seen in the preceding code example) and XHTML 1.0.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The HTML DOCTYPE declaration

The first line of your HTML page will contain the DOCTYPE declaration. This is used to tell the browser how the HTML page should be interpreted. We'll focus on HTML5 in this book, so the following example you see uses the HTML5 DOCTYPE declaration. The two other common DOCTYPE declarations are HTML 4.01 Strict and XHTML 1.0 Strict:

  • HTML 5 uses the following code:

    <!DOCTYPE html>
  • HTML 4.01 Strict uses the following code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  • XHTML 1.0 Strict uses the following code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

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 the helloworld.html page in a browser will produce the content you see in the following screenshot. Most of the ArcGIS API for JavaScript code that you write will be placed between the <head></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 JavaScript section. We'll explore this topic later. For now, just concentrate on placing your code inside the <head> tags.

Validating HTML code

As mentioned earlier, it is very important that your HTML tags be coded correctly. This is all well and good you say, but how do I know that 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 following screenshot can be used to validate HTML code through URI, file upload, or direct input:

Assuming that your HTML code successfully validates itself, you will get a screen with a message indicating a successful validation as shown in the following screenshot:

On the other hand, it will identify any problem with an error message displayed in red. 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. Don't panic if this is the case. Fixing one error often resolves many others.

To correct the errors in the preceding document, you would need to surround the text Hello World with a paragraph tag similar to <p>Hello World</p>.

 

JavaScript fundamentals


As implied by the name, the ArcGIS 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 you start building 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 us 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 user-friendly. However, JavaScript does have the capability of submitting requests to the server, and is a core technology in the Asynchronous JavaScript and XML (AJAX) stack.

Note

One common misconception regarding JavaScript is that it is a simplified version of Java. The two languages are actually unrelated with the exception of the name.

Commenting in code

It is a best practice to always document your JavaScript code through the use of comments. At a minimum, these should include the author of the code, the date of last revision, and the general purpose of the code. In addition, at various points throughout your code, you should include comment sections that define the purpose of specific sections of the application. The purpose of this documentation is to make it easier for you or any other programmer to quickly get up to speed in the event that the code needs to be updated in some way.

Any comments that you include in your code are not executed. They are simply ignored by the JavaScript interpreter. Commenting in JavaScript can be done in a couple of ways including single line and multiline comments. Single line comments start with // and any additional characters that you add to the line. The following code example shows how single line comments are created:

//this is a single line comment.  This line will not be executed

Multiline comments in JavaScript start with /* and end with */. Any lines in between are treated as comments and are not executed. The following code example shows an example of multiline comments:

/*
 Copyright 2012 Google Inc.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

Variables

The concept of variables is 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 computer's memory that store data.

You can think of a variable as a box that has a name and 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 following diagram, we create a variable called ssn. Initially, this variable is empty but is then assigned a value of 450-63-3567. The data value assigned to a variable can be of various types, including numbers, strings, booleans, objects, and arrays.

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 an 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 to. It is also perfectly legal to declare multiple variables with the same var keyword as seen in the following code example:

var i, j, k;

You can also combine variable declaration with data assignment, as seen in the following examples:

var i = 10;
var j = 20;
var k = 30;

You may have also noticed that each JavaScript statement ends with a semicolon. The semicolon indicates the end of a statement in JavaScript and should always be included in JavaScript.

JavaScript and case sensitivity

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 the 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. In the following code snippet, 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 = 'John';
var MyName = 'Joe';

Variable datatypes

JavaScript supports various types of data that can be assigned to your variables. Unlike other strongly-typed languages such as .NET or C++, JavaScript is a loosely-typed language. What this means is that you don't 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 straightforward for the most part. Strings are simply text enclosed by either a single or double quote. For instance:

varbaseMapLayer = "Terrain";
varoperationalLayer = '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 use 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 datatype while a value of 3.14 with single or double quotes is assigned a string data type.

Other datatypes include booleans that are simply true or false values and arrays that 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 required.

Arrays allow you to store multiple values in a single variable. For example, you might want to store the names of all the layers you want to add to a map. Instead of creating individual variables for each layer, you could use an array to store all of them in a single variable. You can then reference individual values from the array using an index number by looping through them with a for loop. The following code example shows one way to create an array in JavaScript:

var myLayers=new Array(); 
myLayers[0]="Parcels";       
myLayers[1]="Streets";
myLayers[2]="Streams";

You could also simplify the creation of this array variable as seen in the following code example, where the array has been created as a comma-separated list enclosed in brackets:

var myLayers = ["Parcels", "Streets", "Streams"];

You can access elements in an array through the use of an index as seen in the following code example. Array access is zero based, which means that the first item in the array occupies the 0 position and each successive item in the array is incremented by one:

var layerName = myLayers[0];  //returns Parcels

Decision-supporting statements

An if/else statement in JavaScript and other programming languages is a control statement that allows decision making in your code. This type of statement performs a test at the top of the statement. If the test returns a value of true, then the statements associated with the if block will run. If the test returns a value of false, then the execution skips to the first else if block. This pattern will continue until a value of true is returned in the test or the execution reaches the else statement. The following code example shows how this statement works:

var layerName = 'streets';
if (layerName == 'aerial') {
    alert("An aerial map");
}
else if (layerName == "hybrid") {
    alert("A hybrid map");
}
else {
    alert("A street map");
}

Looping statements

Looping statements give you the ability to run the same block of code over and over again. There are two fundamental looping mechanisms in JavaScript. The for loop executes a code block a specified number of times and the while loop executes a code block while a condition is true. Once the condition becomes false, the looping mechanism stops.

The following code sample shows the syntax of a for loop. You'll note that it takes a start value, which will be an integer and a condition statement. You can also supply an increment. The code block inside the for loop will execute the given condition while the value is less than the end value:

for (start value; condition statement; increment)
{
  the code block to be executed
 }

In the following example, the start value is set to 0 and is assigned to a variable called i. The condition statement is when i is less than or equal to 10, and the value of i is incremented by 1 for each loop, using the ++ operator. Each time we pass through the loop, the value of i is printed:

var i = 0;
for (i = 0; i <= 10; i++) {
    document.write("The number is " + i);
    document.write("<br/>");
}

The other basic looping mechanism in JavaScript is the while loop. This loop is used when you want to execute a code block while a condition is true. Once the condition is set to false, the execution stops. The while loops accept a single argument, which is the condition that will be tested. In the following example, the code block will be executed while i is less than or equal to 10. Initially, i is set to a value of 0. At the end of the code block, you will notice that i is incremented by one (i = i + 1):

var i = 0;
while (i <= 10)
{
    document.write("The number is " + i);
    document.write("<br/>");
    i = i + 1;
}

Functions

Now let's cover the very important topic of functions. Functions are simply named blocks of code that are executed when called. The vast majority of the code that you write in this book and in your development efforts will occur within the functions.

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 is loaded.

To create a function, you need to use the function keyword followed by a function name that you define, and any variables necessary for the execution of the function passed as parameter 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 that you want passed back.

Functions can also accept parameters that are just variables used to pass information into the function. In the following code example, the prod() function passes two variables: a and b. This information, in the form of variables, can then be used inside the function:

var x;
function multiplyValues(a,b){
    x = a * b;return x;
}

Objects

Now that we've gone through some basic JavaScript concepts, we'll tackle the most important concept in this section. In order to effectively program mapping applications with the ArcGIS 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 API for JavaScript makes extensive use of objects. We'll cover the details of this programming library in detail, but for now we'll 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 datatypes, such as 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 API for JavaScript, 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 others. These properties contain information about the object.

Objects also have actions that we typically call 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.

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 into the constructor to give more control over the object that is created. The following code example shows how a constructor is used to create a new instance of a Map object. You can tell that this method is a constructor because of the use of the new keyword that I've highlighted. The new keyword, followed by the name of the object and any parameters used to control the new object, defines the constructor for the object. In this case, we've created a new Map object and stored it in a variable called map. Three parameters are passed into the constructor to control various aspects of the Map object including basemap, center of the map, and the zoom scale level:

var map = new Map("mapDiv", { 
  basemap: "streets",
  center:[-117.148, 32.706], //long, lat
  zoom: 12
});

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 a 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. A couple of code examples showing how to access properties of an object are as follows:

var theExtent = map.extent;
var graphics = map.graphics;

The same is the case with methods, except that methods have parentheses at the end of the method name. Data can be passed into a method through the use of parameters. In the first line of the following code, we're passing a variable called pt into the map.centerAt(pt) method:

map.centerAt(pt);
map.panRight();
 

Basic CSS principles


Cascading Style Sheets (CSS) 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. Take a look at the following code snippet:

<style>
  html, body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
  }
  
  #map{
    
    padding:0;
    border:solid 2px #94C7BA;
    margin:5px;
  }
  #header {
    border: solid 2px #94C7BA;
    padding-top:5px;
    padding-left:10px;
    background-color:white;
    
    color:#594735;
    
    font-size:14pt;
    text-align:left;
    font-weight:bold;
    height:35px;
    margin:5px;
    overflow:hidden;
  }
  .roundedCorners{
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
  }
  .shadow{
    
    -webkit-box-shadow: 0px 4px 8px #adadad;
    -moz-box-shadow: 0px 4px 8px #adadad;
    -o-box-shadow: 0px 4px 8px #adadad;
    box-shadow: 0px 4px 8px #adadad;
  }
</style>

CSS syntax

CSS follows certain rules that define what HTML element to select along with defining how that element should be styled. A CSS rule has two main parts: a selector and one or more declarations. The selector is typically the HTML element that you want to style. In the following diagram, the selector is p. A <p> element in HTML represents a paragraph. The second part of a CSS rule comprises of 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 define that all the text within our paragraph should be in red.

We have used p {color:red}, as shown in the following diagram:

You can include more than one declaration in a CSS rule as you see in the following example. A declaration is always surrounded by curly brackets and each declaration ends with a semicolon. 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 semicolon:

p {color:red;text-align:center}

CSS comments are used to explain your code. You should get into the habit of always commenting on your CSS code just as you would in any other programming language. Comments are always ignored by the browser. 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:

/*
h1 {font-size:200%;}
h2 {font-size:140%;}
h3 {font-size:110%;}
*/

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 instance, in the following code example, you see three id selectors: rightPane, leftPane, and map. In ArcGIS 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 selector and assign it a value that is often the word 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:

#rightPane {
    background-color:white;
    color:#3f3f3f;
    border: solid 2px #224a54;
    width: 20%;
}
#leftPane {
    margin: 5px;
    padding: 2px;
    background-color:white;
    color:#3f3f3f;
    border: solid 2px #224a54;
    width: 20%;
}
#map {
    margin: 5px;
    border: solid 4px #224a54;
    -mox-border-radius: 4px;
}

Unlike id selectors that are used to assign styles to a single element, the 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 following code example:

.center {text-align:center;}
p.center {text-align:center;}

Your HTML code would then reference the class selector as follows:

<p class="center">This is a paragraph</p>

There are three ways to insert CSS into your application: inline, internal stylesheets, and external stylesheets.

Inline styling

The first 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 in some cases where you need to define a very limited set of CSS rules. To use inline styles, simply place the style attribute inside the relevant HTML tag:

<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Internal stylesheets

An internal stylesheet 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 are enclosed inside a <style> tag, as seen in the following code example:

<head>
    <style type="text/css">
        hr {color:sienna;}
        p {margin-left:20px;}
        body {background-image:url("images/back40.gif");}
    </style>
</head>

External stylesheets

An external stylesheet is simply a text file containing CSS rules and is saved with a .css file extension. This file is then linked to all web pages that want to implement the styles defined within the external stylesheet through the use of the HTML <link> tag. This is a commonly used method to split 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 stylesheet.

Now let's put some emphasis on the cascading part of cascading stylesheets. As you now know, styles can be defined in external stylesheets, internal stylesheets, or inline. There is a fourth level that we didn't discuss, which is the browser default. You don't 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 stylesheet, an external stylesheet, or the browser default. If an inline style is not defined, any style rule defined in an internal stylesheet would take precedence over styles defined in an external stylesheet. The caveat here is that if a link to an external stylesheet is placed after the internal stylesheet in HTML <head>, the external stylesheet will override the internal sheet!

That's a lot to remember! Just keep in mind that style rules defined further down the hierarchy override style rules defined higher in the hierarchy, as shown in the following diagram:

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.

 

Separating HTML, CSS, and JavaScript


You may be wondering where all of this code is placed. Should you put all your HTML, CSS, and JavaScript code in the same file or split them into separate files? For very simple applications and examples, it is not uncommon for all the code to be placed into a single file with an extension of .html or .htm. In this case, the CSS and JavaScript code will reside in the <head> section of your HTML page. However, the preferred way of creating an application using this code stack is to separate the presentation from the content and behavior. The user interface items for your application should reside in an HTML page that contains only tags used to define the content of the application, along with references to any CSS (presentation) or JavaScript (behavior) files that are part of the application. The end result is a single HTML page and one or more CSS and JavaScript files. This would result in a folder structure similar to that shown in the following screenshot, where we have a single file called index.html and several folders that hold CSS, JavaScript, and other resources, such as images. The css and js folders will contain one or more files.

CSS files can be linked into an HTML page with the <link> tag. In the following code sample, you will see a code example that shows you how to use the <link> tag to import a CSS file. Links to CSS files should be defined in the <head> tag of your HTML page:

<!DOCTYPE html>

<html>
  <head>
    <title>GeoRanch Client Portal</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="bootstrap/css/bootstrap.css">
  </head>
  <body>
  </body>
</html>

JavaScript files are imported into your HTML page with the <script> tag as seen in the following code example. These <script> tags can be placed in the <head> tag of your web page, as seen in reference to the ArcGIS API for the following JavaScript code, or near the end of the page just before the ending </body> tag, as has been done with the creategeometries.js file. It is often recommended that you import your JavaScript files close to the ending </body> tag because when browsers download JavaScript files, they don't download anything else until the downloading is done. This can make it look like the application is loading slowly.

Adding a <script> tag in the header is recommended for JavaScript libraries, such as Dojo, which need to be parsed before they interact with HTML elements in the body. That's why the ArcGIS API for JavaScript is loaded in the header:

<!DOCTYPE html>
<html>
  <head>
    <title>GeoRanch Client Portal</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">


    <script src="http://js.arcgis.com/3.7/"></script>
  </head>
  <body>
    <script src="js/creategeometries.js"></script>
  </body>
</html>

Splitting your code into several files allows for a clean separation of your code and it should be much easier to maintain.

 

Summary


Before we can begin a detailed discussion of the ArcGIS API for JavaScript, you need to have an understanding of some of the fundamental HTML, CSS, and JavaScript concepts. This chapter has provided just that, but you will need to continue learning many additional concepts related to these topics. Right now, you know just enough to be dangerous.

How your application looks is defined through the HTML and CSS code that you develop while the functionality provided by your application is controlled through JavaScript. These are very different skill sets and many people are good at one but not necessarily the other. Most application developers will focus on developing the functionality of the application through JavaScript and will leave HTML and CSS to the designers! Nevertheless, it is important that you have a good understanding of at least the basic concepts of all these topics. In the next chapter, we'll dive into the ArcGIS API for JavaScript and begin learning how to create the Map object and how to add dynamic and tiled map service layers to the map.

About the Author

  • Eric Pimpler

    Eric Pimpler is the founder and owner of GeoSpatial Training Services and has over 20 years of experience in implementing and teaching GIS solutions using Esri, Google Earth/Maps, and open source technology. Currently, he focuses on ArcGIS scripting with Python and the development of custom ArcGIS Server web and mobile applications using JavaScript. He is the author of Programming ArcGIS 10.1 with Python Cookbook. Eric has a bachelor's degree in geography from Texas A&M University and a master's degree in applied geography with a specification in GIS from Texas State University.

    Browse publications by this author

Latest Reviews

(5 reviews total)
Delving into Java then this guide makes a perfect companion!
Very helpful book, especially for my lectures
Excellent
Book Title
Unlock this book and the full library for FREE
Start free trial