Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition

You're reading from   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

Arrow left icon
Product type Paperback
Published in Oct 2017
Publisher Packt
ISBN-13 9781787280526
Length 324 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Eric Pimpler Eric Pimpler
Author Profile Icon Eric Pimpler
Eric Pimpler
Mark Lewin Mark Lewin
Author Profile Icon Mark Lewin
Mark Lewin
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Introduction to HTML, CSS, and JavaScript FREE CHAPTER 2. Creating Maps and Adding Layers 3. Adding Graphics to the Map 4. The Feature Layer 5. Using Widgets and Toolbars 6. Performing Spatial and Attribute Queries 7. Identifying and Finding Features 8. Turning Addresses into Points and Points into Addresses 9. Directions and Routing 10. Geoprocessing Tasks 11. Geometry Operations 12. Integration with ArcGIS Online 13. Creating Mobile Applications 14. Looking Ahead - Version 4 of the ArcGIS API for JavaScript

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(); 
You have been reading a chapter from
Building Web and Mobile ArcGIS Server Applications with JavaScript ??? Second Edition - Second Edition
Published in: Oct 2017
Publisher: Packt
ISBN-13: 9781787280526
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime