Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition
Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition

Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition: Build exciting custom web and mobile GIS applications with the ArcGIS Server API for JavaScript , Second Edition

Arrow left icon
Profile Icon Eric Pimpler Profile Icon Mark Lewin
Arrow right icon
$54.99
Paperback Oct 2017 324 pages 2nd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Eric Pimpler Profile Icon Mark Lewin
Arrow right icon
$54.99
Paperback Oct 2017 324 pages 2nd Edition
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

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

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.

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.

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.

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.

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

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Develop ArcGIS Server applications with JavaScript, both for traditional web browsers as well as the mobile platform
  • • Make your maps informative with intuitive geographic layers, user interface widgets, and more
  • • Integrate ArcGIS content into your custom applications and perform analytics with the ArcGIS Online

Description

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.

Who is this book for?

If you are a web or mobile application developer, who wants to create GIS applications in your respective platform, this book is ideal for you. You will need Java Script programming experience to get the most out of this book. Although designed as an introductory to intermediate level book, it will also be useful for more advanced developers who are new to the topic of developing applications with ArcGIS Server.

What you will learn

  • • To create an application with the ArcGIS API for JavaScript
  • • Build and display a broad range of different geometry types to represent features on the map
  • • The best way to leverage a feature layer and display related attribute data
  • • The functionality of the wide range of widgets and how to use them effectively
  • • Query data to gain new insights into the information it contains
  • • Work with tasks to discover and locate features on the map
  • • Using the geocoder and associated widgets
  • • The ability of the API to provide turn by turn directions and routing capabilities
  • • How to use the Geometry Engine and Geometry Service tasks for common geoprocessing operations
  • • Integrate content on ArcGIS online and add it to your custom web mapping application
Estimated delivery fee Deliver to Russia

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 24, 2017
Length: 324 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787280526
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Russia

Economy delivery 10 - 13 business days

$6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Oct 24, 2017
Length: 324 pages
Edition : 2nd
Language : English
ISBN-13 : 9781787280526
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 164.97
ArcPy and ArcGIS
$54.99
Mastering ArcGIS Enterprise Administration
$54.99
Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition
$54.99
Total $ 164.97 Stars icon
Banner background image

Table of Contents

14 Chapters
Introduction to HTML, CSS, and JavaScript Chevron down icon Chevron up icon
Creating Maps and Adding Layers Chevron down icon Chevron up icon
Adding Graphics to the Map Chevron down icon Chevron up icon
The Feature Layer Chevron down icon Chevron up icon
Using Widgets and Toolbars Chevron down icon Chevron up icon
Performing Spatial and Attribute Queries Chevron down icon Chevron up icon
Identifying and Finding Features Chevron down icon Chevron up icon
Turning Addresses into Points and Points into Addresses Chevron down icon Chevron up icon
Directions and Routing Chevron down icon Chevron up icon
Geoprocessing Tasks Chevron down icon Chevron up icon
Geometry Operations Chevron down icon Chevron up icon
Integration with ArcGIS Online Chevron down icon Chevron up icon
Creating Mobile Applications Chevron down icon Chevron up icon
Looking Ahead - Version 4 of the ArcGIS API for JavaScript Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela