Building Web and Mobile ArcGIS Server Applications with JavaScript - Second Edition

4.5 (2 reviews total)
By Eric Pimpler , Mark Lewin
  • 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

The ArcGIS API for JavaScript enables you to quickly build web and mobile mapping applications that include sophisticated GIS capabilities, yet are easy and intuitive for the user.

Aimed at both new and experienced web developers, this practical guide gives you everything you need to get started with the API. After a brief introduction to HTML/CSS/JavaScript, you'll embed maps in a web page, add the tiled, dynamic, and streaming data layers that your users will interact with, and mark up the map with graphics. You will learn how to quickly incorporate a broad range of useful user interface elements and GIS functionality to your application with minimal effort using prebuilt widgets. As the book progresses, you will discover and use the task framework to query layers with spatial and attribute criteria, search for and identify features on the map, geocode addresses, perform network analysis and routing, and add custom geoprocessing operations. Along the way, we cover exciting new features such as the client-side geometry engine, learn how to integrate content from ArcGIS.com, and use your new skills to build mobile web mapping applications.

We conclude with a look at version 4 of the ArcGIS API for JavaScript (which is being developed in parallel with version 3.x) and what it means for you as a developer.

Publication date:
October 2017
Publisher
Packt
Pages
324
ISBN
9781787280526

 

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 only going to cover these topics at a very basic level. Just enough to get you started. For a more advanced treatment of any of these subjects there are many learning resources available including books and online tutorials. Please consult Appendix 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 JavaScript file. HTML files typically have a file extension of .html or .htm and JavaScript files have an extension of .js. Once you have created a basic HTML page you can then go through the necessary steps to create a basic map with the ArcGIS 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 further down the line when your JavaScript code attempts to access these 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>:

<!DOCTYPE html> 
<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 number of flavors of HTML currently in use. Most new HTML pages developed today use HTML5, so we'll focus on HTML5 throughout the book, but without delving into many of its advanced features. Other versions of HTML you are likely to encounter in the wild include HTML 4.0.1 and XHTML 1.0.

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. We'll focus on HTML5 in this book so the first example you see in the following uses the HTML5 DOCTYPE. The two other common doctypes are HTML 4.01 Strict and XHTML 1.0 Strict:

  • HTML5:
<!DOCTYPE html>    
  • HTML 4.01 Strict:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  • XHTML 1.0 Strict:
<!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 this HTML page in a browser would 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, either within a <script> tag or inside a separate JavaScript file. As you gain experience you will likely begin placing your JavaScript code inside one or more JavaScript files and then referencing them from the <head> section. We'll explore this topic later. For now just concentrate on placing your code inside <script> tags, within the <head> tags:

Validating HTML code

I've 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 following screenshot can be used to validate HTML code by URI, File Upload, or Direct Input:

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

On the other hand, it will identify any problems with a red error message as shown in the following screenshot. 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 paragraph tags:

<p>Hello World</p>
 

JavaScript fundamentals


As the name implies, 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 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 best known for its integration with web applications.

All modern web browsers including Chrome, Firefox, Safari, and Edge have JavaScript embedded. The use of JavaScript in web applications enables the creation of dynamic applications that do not require round trips to the server to fetch data, and thus the applications are more responsive and feel like native applications. However, JavaScript can submit requests to the server for more (or more up-to-date) information, and is a core technology in the AJAX (Asynchronous JavaScript and XML) stack.

Note

One common misconception regarding JavaScript is that it is actually a simplified version of Java. The two languages are actually unrelated: only the names and C-like syntax are similar.

Commenting code

It is best practice to always document your JavaScript code through the use of comments. At a minimum, this should include the author of the code, 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 another 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. JavaScript can be commented in a couple of ways including single line and multi-line comments. Single line comments start with//and any additional characters 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

Multi-line 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 multi-line comments (also called block 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

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 a 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 that 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 figure, 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 adhere to when creating a variable:

  • Variable names can contain both text and numbers, but should never start with a number. Always start your variable name with a letter or underscore.
  • Spaces are not permitted. If you want your variable name to include multiple words, use camel case notation. This convention requires using lower case for the first word, and capitalizing the first letter of subsequent words. For example: myVariableName .
  • Special characters such as percentage signs and ampersands are not allowed within variable names. Underscores, however, are permitted and can appear anywhere within the variable name.

Other than that, you are free to create variable names as you wish but you should try to assign variable names that describe the data that the variable will be assigned. It is also perfectly legal to declare multiple variables with the same var keyword as seen in the following code example:

var i, j, k; 

You can also combine variable declarations with data assignments, 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. Missing semicolons are the cause of many JavaScript programming errors.

JavaScript is case sensitive

One very important point that we need to be clear about is that JavaScript is a case-sensitive language. You must 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. 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 as follows:

var myName = 'Eric';
var myname = 'John';
var MyName = 'Joe';

Variable data types

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 straight forward for the most part. Strings are simply text enclosed by either a single or a 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 we 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 data type while a value of "3.14" with single or double quotes is assigned a string data type.

Other data types 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 each element in the array 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. Rather than 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, or by looping through them with a for loop. The following code example shows how to create an array in JavaScript and reference its individual members via their index values:

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

Bear in mind that if you access array elements via their index, the index numbering is zero-based. This means that the first item in the array occupies position 0 and each successive item in the array is incremented by one:

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

Decision support statements

An if/else statement in JavaScript and other programming languages is a control statement that allows for decision-making in your code. This type of statement performs a test based on an expression, that you specify 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 continues 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 syntax of a for loop is shown as follows. You'll note that it takes a start value for the loop counter that is an integer and a condition expression that, if it evaluates to false, will cause the loop to terminate. You should also supply an increment that increases the value of the loop counter on each iteration of the loop:

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 iteration of the loop using the ++ operator. The code in the body of the loop prints the value of i for the current iteration:

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, execution stops. while loops accept a single argument which is the condition expression that will be tested. In the following example, the code block will execute 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; 
} 

The while loop repeats until i reaches the value of 11.

Functions

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

Best practice calls for you to split your code into functions that perform small, discrete tasks. These blocks of code are normally defined in the <head> section of a web page inside a <script> tag, but can also be defined in the <body> section. However, in most cases you will want your functions defined within the <head> section so that you can ensure that they are available once the page has loaded.

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

Functions can also accept parameters which are just variables that are used to pass information into the function. In the following code example, the multiplyValues() function is passed two variables: a and b. This information, in the form of variables, can then be used inside the function which, in this instance, returns the product of a and b, which is assigned to the variable x:

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 before moving forward.

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 focus on the high-level concepts. Objects are complex structures capable of aggregating multiple data values and actions into a single structure. This differs greatly from our primitive data types such as numbers, strings, and Booleans which can hold only a single value.

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, layers associated with the map, and so on. These properties contain information about the object.

Objects also have actions which 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 which 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 particular 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 the 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 clicking on the map, panning the map, 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 following examples demonstrate how to access an object's properties:

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 following first line of code, we're passing a variable called pt into the map.centerAt(pt) method:

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

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:

<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 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 example, the selector is p. A <p> element in HTML represents a paragraph. The second part of a CSS rule is one or more declarations, each of which consists of a property and a value. The property represents the style attribute that you want to change. In our example, we are setting the color property to red. In effect, what we have done with this CSS rule is to define that all text within our paragraph should be red p {color:red}:

Here is an example of a CSS rule:

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

You can include more than one declaration in a CSS rule as you see in the preceding 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.

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 begin with a slash followed by an asterisk and end with an asterisk followed by a slash. In this way, they are identical to block comments in JavaScript. Everything in between those markers is assumed to be a comment and is ignored by the browser:

/* 
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 example, 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 specify an id and assign it a value which 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; 
} 

This results in the following layout:

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

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

This approach is useful if you want to group the styling of several HTML elements which are of different types.

Note

There are three ways to insert CSS into your application: inline, or by using internal or external style sheets.

Inline styling

One way 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:

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

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

Internal style sheet

An internal style sheet moves all the CSS rules into a specific web page. Only HTML elements within that particular page have access to the rules. All CSS rules are defined inside the <head> tag and enclosed inside a <style> tag, as seen in the code example as follows:

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

External style sheet

An external style sheet is simply a text file containing CSS rules and saved with a file extension of .css. This file is then linked into all web pages that want to implement the styles defined within the external style sheet through the use of the HTML <link> tag. This is a commonly used method for splitting out the styling from the main web page and gives you the ability to change the look of an entire website through the use of a single external style sheet.

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

That's 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.

 

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 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 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 with the reference to the ArcGIS API for JavaScript near the end of the page just before the ending </body> tag, as has been done with the creategeometries.js file:

<!DOCTYPE html>
<html>
    <head>
        <title>GeoRanch Client Portal</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <script src="https://js.arcgis.com/3.20/"></script>
    </head>
    <body>
        <script src="js/creategeometries.js"></script>
    </body>
</html> 

Some developers recommend importing your JavaScript files close to the ending </body> tag. This is because, when rendering an HTML page, the browser considers each line of HTML in turn and does not proceed to the next line until the current one has been processed. If you load large external JavaScript files in the <head> section, then the user will just see a blank page until the script has fully loaded. Their rationale is that if these files are loaded last, the user will at least see something rendered on the page while they are being downloaded. In the authors' opinion, this is not usually a problem for most users because connection speeds are normally so good that even large external files are downloaded almost instantaneously. Do bear it in mind though.

Putting a <script> in the <head> section is recommended when using JavaScript libraries like Dojo that must be parsed before they can interact with HTML elements in the <body> section. That's why we always reference the ArcGIS API for JavaScript in the <head> section.

Note

The Dojo Toolkit is an open source modular JavaScript library, designed to enable the rapid development of web applications. The ArcGIS API for JavaScript is built upon Dojo, so we will be talking about it extensively in this book. Find out more about Dojo here: https://dojotoolkit.org/.

Note

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.

The visual appearance of your application is defined through the HTML and CSS code that you develop, while its functionality is controlled using 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 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 add dynamic and tiled map service layers to the map.

About the Authors

  • 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
  • Mark Lewin

    Mark Lewin has been developing, teaching, and writing about software for over 16 years. His main interest is GIS and web mapping. Working for ESRI, the world's largest GIS company, he has been a consultant, trainer and course author, and a frequent speaker at industry events. He has subsequently expanded his knowledge to include a wide variety of open source mapping technologies and a handful of relevant JavaScript frameworks, including Node.js, Dojo, and JQuery. Mark now works within Oracle's MySQL curriculum team, focusing on creating great learning experiences for DBAs and database developers, but remains crazy about web mapping.

    Browse publications by this author

Latest Reviews

(2 reviews total)
Muy buen libro. Actualizado. Lo recomiendo.
Great book and best price!!!

Recommended For You

JavaScript and JSON Essentials - Second Edition

Use JSON for building web applications with technologies like HTML, JavaScript, Angular, Node.js, Hapi.js, Kafka, socket.io, MongoDB, Gulp.js, and handlebar.js, and others formats like GEOJSON, JSON-LD, MessagePack, and BSON.

By Bruno Joseph D'mello and 1 more
Learning JavaScript Data Structures and Algorithms - Third Edition

Create classic data structures and algorithms such as depth-first search and breadth-first search, learn recursion, as well as create and use a heap data structure using JavaScript

By Loiane Groner
Reactive JavaScript Programming [Video]

Change the way you code: become efficient and up-to-date with an in depth coverage of Reactive JavaScript programming techniques

By Shriyans Bhatnagar
Mastering ArcGIS Enterprise Administration

Learn how to confidently install, configure, secure, and fully utilize your ArcGIS Enterprise system.

By Chad Cooper