JavaScript is the most popular programming language today, largely because it is the only programming language that is available in all major browsers. With JavaScript you can make web pages dynamic with animations, buttons that change other items on the page, and interact with the user with dialog boxes and pop-ups.
JavaScript is a scripting language so it is not as fast as C++ or Java but it is remarkably fast for a scripting language. We can't really do heavy image processing and spatial analysis inside a browser so the speed of JavaScript is not really a limitation.
This introduction is for folks with some experience with programming.
To start, enter the following code into the "head" portion of an HTML page and open it in a browser. You may get a message from the browser asking for permission to run the page.
<script> var x=12; var y=2; var z=x+y; alert(z); </script>
You should see a dialog box appear with the correct answer. In JavaScript, all variables are defined with the "var" word, short for "variable". Also, all "statements" must end in a semicolon (";"). In other programming languages, we'd use a "print()" function to output basic results but we don't have anywhere to print to (yet) so we'll use "alert()" for now and we'll look at other approaches in future lessons.
Try different numbers for "x" and "y" and see if the answers are what you expect. Then, try different mathematical operators such as:
Symbol | Description |
---|---|
+ | plus, addition |
- | minus, subtraction |
* | multiply |
/ | divide |
There are a number of mathematical definitions and functions available in JavaScript in the "Math" library. Try the following and then try different values and see what the results are:
<script> var x=Math.PI/4; var y=Math.sin(x); alert(y); </script>
Your best resource for learning JavaScript is W3Schools. Visit their Math Object page for more information.
All of the modern browsers have source-code debuggers built into them. In Chrome you can click on the vertical line of 3 dots and select "More Tools -> Developer Tools", in Firefox, select "Tools -> Web Developer -> Toggle Tools". In both cases, this will open a debugging panel that shows you what is happening "behind the scenes" in the browser. Open the debugging in Chrome now with one of the code samples above. You'll see something like the screen below. I'm only going to show you how to work with the most commonly used features for now. At the top of the window are two tabs "Elements" and "Sources". The Elements panel shows you the contents of the DOM and we'll look at it next week. The Source panel shows any errors the browser found in your code and allows you to "step" through your code to find out what is causing the problems.
The image below shows the console and the icons indicate errors, warnings, and information from left to right. Errors will stop the page from working and so it's very important to check the console regularly if you are having problems getting your scripts to work. Warnings are frequent but will not stop the page from working. You can pretty much ignore the informational messages.
Note: You may get an error in the debugger on the "WEB_PAGE" content. This is actual an error from an extension that can be installed in Chrome.
For any errors, you'll see the file and line number the error occurred on. You can click on the line with this information to jump into the debugger at that point. Typically, you'll then create a break point and refresh the web page to recreate the error.
To stop the debugger on a line of code, just click in the gray area next to the code line you want to stop on. A blue bar (a red circle in all other debuggers) should appear. In the image below, the arrow indicates we have stopped on line 7. To remove a breakpoint, just click on it again. Once a program has "broken" it will "pause" and wait for your commands. Then, you can "step into" a function, "step over" a function to continue by pressing "go". As you "step" through your code, you can examine the variables on the right.
These debuggers are relatively new and I've crashed all of them. When they stop working, it's back to putting in "alerts" to track down defects
Call the alert function is handy for critical errors but it gets annoying when we want to print out a lot of information when debugging. For this, we'll use the "console.log()" function:
<script> var x=Math.PI/4; var y=Math.sin(x); console.log(y); </script>
All text in JavaScript is handled as "string" of "characters". Each letter, number or symbol is one character. JavaScript allows us to create strings of characters and then "concatenate" them together with the plus ("+") sign.
<script> var StartText="Thank God men cannot fly, "; var TheText=StartText+"and lay waste the sky as well as the earth."; TheText=TheText+"? Henry David Thoreau "; console.log(TheText); </script>
There are a number of properties and functions available for string processing. Try each of the steps below until you feel you have an idea of how they are working:
<script> var StartText="Thank God men cannot fly, "; // create a string var TheText=StartText+"and lay waste the sky as well as the earth."; // create a new string from concatenating the string to another string TheText=TheText+" - Henry David Thoreau "; var TheNumberOfCharacters=TheText.length; // get the length of a string console.log(TheNumberOfCharacters); var Index=TheText.indexOf("as well as"); // find text within a string console.log(Index); var StartString=TheText.substring(0,Index); // cut out the characters from 0 (start of the string) to Index console.log(StartString); var EndString=TheText.substring(Index+11); // cut out the characters from Index to the end of the string console.log(EndString); var NewString=StartString+" and "+EndString; // concatenate three strings together console.log(NewString); </script>
For additional information on strings, consult the W3Schools web page on Strings .
The variables are variant types and the type will change with the type of data you assign to it. Try the following:
<script> var x=12; var TheType=typeof(x); console.log(TheType); var y="Hello"; var TheType=typeof(y); console.log(TheType); </script>
You should have seen "number" and then "string".
Types can get us into trouble in JavaScript. Pause for a moment and as your self what is "1+1" and then execute the code below.
<script> var x=1+"1"; console.log(x); </script>
If you're surprised you got "11", take a look at what is being put into "x" and remember that COMPUTERS ARE STUPID! In this case, the computer took the numeric value of 1 and "concatenated" it with the string "1". JavaScript only concatenates strings so, to up us out, it converted the number to a string. This can cause serious headaches down the road. When in doubt, use the "typeof()" function to determine the types of variables.
If you have text with a number in it, you may need to convert it to a number for calculations. This can be done with the parseInt() or parseFloat() functions.
<script> var IntegerNumber=parseInt("12"); var FloatingPointNumber=parseFloat("12.34"); </script>
In going through the examples above, you probably got tired of seeing the "alert" messages pop-up over and over. In JavaScript, you can comment out the rest of a line with two forward slashes ("//"). Try this now with one of the samples. This is used to comment out lines and add comments to the end of a line as below
<script> var x=1+"1"; // this line just has a comment at the end of it //console.log(x); // this line is commented out </script>
For larger blocks of comments you can "/*" at the start of the block and */ at the end. You'll need this to add headers to your files like the following:
/** * File with some example code by Jim Graham * Date: 8/23/2015 */
This the standard way to document JavaScript and we'll talk more about it later.
One of the common tasks in web based GIS is formatting coordinates. Let's pretend that we were given some coordinates in DD and we need to present them in DMS. First, we need to find the HTML characters for degrees and a quick web search shows that it is "°" (yep, this is what the browsers expect!). Then, the code is not that complicated:
<script> var DD=-120.12345; var Degrees=Math.floor(DD); // get the whole portion of the degrees var RemainderInMinutes=(DD-Degrees)*60; // convert the remaining portion to minutes var Minutes=Math.floor(RemainderInMinutes); // get the whole portion of the minutes var Seconds=Math.floor((RemainderInMinutes-Minutes)*60); // convert the remaining portion to seconds var Text=Degrees+"°"+" "+Minutes+"' "+Seconds+"\""; console.log(Text); </script>
The degree did not turn out exactly as we hoped but it will look good when we use it in an HTML element instead of the "console.log()" function. The problem is that we probably don't want to type this code over and over every time we want to print out a value. That's where functions come in.
<script> function ConvertToDMSText(DD) { var Degrees=Math.floor(DD); var RemainderInMinutes=(DD-Degrees)*60; var Minutes=Math.floor(RemainderInMinutes); var Seconds=Math.floor((RemainderInMinutes-Minutes)*60); var Text=Degrees+"°"+" "+Minutes+"' "+Seconds+"\""; return(Text); } var DMS=ConvertToDMSText(-120.12345); console.log(DMS); var DMS=ConvertToDMSText(40.1111); console.log(DMS); </script>
Make sure you step through this code in the debugger so you see that the value you pass in is different with each call. The values passed in are called "parameters". Then, the function "returns" a result. Functions are key to programming in JavaScript and you'll want to keep this one around for later.
Another way to look at functions is that we could create a function that "makes pie". We could then pass the type of pie we wanted into the function. This would be like ordering a pie at the bakery and then picking up the finished pie. In the example below, we pass different types of fruit into the "MakePie()" function. The function then creates a string with the type of pie and returns it. Try this in the debugger.
/* * A function that "makes pie" */ function MakePie(TypeOfFruit) { var ThePie=TypeOfFruit+" Pie"; // add the word " Pie" to the type of fruit return(ThePie); // return the new text string } // Call the "MakePie()" function var TheApplePie=MakePie("Apple"); console.log(TheApplePie); var TheBerryPie=MakePie("Blackberry and Raspberry"); console.log(TheBerryPie);
Now make some of your own functions. Good functions to have available in GIS include:
The more you program the more you will want to create your own set of functions that you use on your web sites.
© Copyright 2018 HSU - All rights reserved.