Chapter 3
IN THIS CHAPTER
Reviewing code to see preexisting functionality
Writing code by following steps to create your app
Debugging your code by looking for common syntax errors
“Talk is cheap. Show me the code.”
— LINUS TORVALDS
It may not feel like it, but you’ve already done the majority of work toward creating your first web application. You painfully broke down your app into steps, and researched each step to determine functionality and design. As Linus Torvalds, creator of the Linux operator system, said, “Talk is cheap.” So let’s start actually coding.
Before you start coding, do a few housekeeping items. First, ensure that you are doing all of the following:
www.google.com/chrome/browser
.Remembering to enable location services on your browser and computer: To enable location services within Chrome, click on the settings icon (three horizontal lines on the top right of the browser), and click on Settings. Then click on the Settings tab, and at the bottom of the screen click on “Show Advanced settings … ” Under the Privacy menu heading, click on “Content settings … ” and scroll down to Location and make sure that “Ask when a site tries to track your physical location” is selected. You can read more here: support.google.com/chrome/answer/142065
.
To enable location services on a PC no additional setting is necessary, but on a Mac using OS X Mountain Lion or later, from the Apple menu choose System Preferences, then click on the Security & Privacy icon, and click the Privacy tab. Click the padlock icon on the lower left, and select Location Services, and check Enable Location Services. You can read more here: support.apple.com/en-us/ht5403
.
Finally, you need to set up your development environment. To emulate a development environment without instructional content use Codepen.io. Codepen.io offers a free stand-alone development environment, and makes it easy to share your code. Open this URL in in your browser: codepen.io/nabraham/pen/ExnsA
.
With the Codepen.io URL loaded, let us review the development environment, the prewritten code, and the coding steps for you to follow.
The Codepen.io development environment, as shown in Figure 3-1, has three coding panels, one each for HTML, CSS, and JavaScript. There is also a preview pane to see the live results of your code. Using the button at the bottom of the screen, you can hide any coding panel you aren’t using, and the layout of the coding panels can be changed.
Signing up for a Codepen.io account is completely optional, and allows you to fork or save the code you have written, and share it with others.
The Codepen.io development environment includes some prewritten HTML, CSS, and JavaScript code for the McDuck’s app. The prewritten code includes code you have seen in previous chapters, and new code that is explained in the following sections.
The HTML code for the McDuck’s app follows, and includes
Here’s the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>McDuck's App</title>
</head>
<body>
<h1> McDuck's Local Offers</h1>
<!--1. Create a HTML button that when clicked calls the JavaScript getLocation() function -->
<!--Two containers, called divs, used to show messages to user -->
<div id="geodisplay"></div>
<div id="effect"></div>
</body>
</html>
The CSS code for the McDuck’s app follows, and includes:
Once your app is functioning, style the app by adding a McDuck’s color scheme and background image logo.
Here’s the CSS:
body {
text-align: center;
background: white;
}
h1, h2, h3, p {
font-family: Sans-Serif;
color: black;
}
p {
font-size: 1em;
}
The JavaScript code for the McDuck’s app follows. This prewritten code is a little complex, because it calculates the current location of the user using the HTML Geolocation API. In this section, I review the code at a high level so you can understand how it works and where it came from.
The Geolocation API is the product of billions of dollars of research and is available to you for free. The most recent browsers support geolocation, though some older browsers do not. At a basic level, code is written to ask whether the browser supports the Geolocation API, and, if yes, to return the current location of the user. When called, the Geolocation API balances a number of data inputs to determine the user’s current location. These data inputs include GPS, wireless network connection strength, cell tower and signal strength, and IP address.
With this in mind, let’s look at the JavaScript code. The JavaScript code includes two functions, as follows:
The getLocation() function: This function determines whether the browser supports geolocation. It does this by using an if statement and navigator.geolocation, which is recognized by the browser as part of the Geolocation API and which returns a true value if geolocation is supported.
Here is the getLocation() function:
function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showLocation);
}
}
The showLocation() function: When the browser supports geolocation, the next step is to call the showlocation function, which calculates and displays the user’s location.
And here is the showLocation() function:
function showLocation(position){
// 2. Hardcode your store location on line 12 and 13, and update the comment to
// reflect your McDuck's restaurant address
// Nik's apt @ Perry & W 4th St (change to your restaurant location)
var mcduckslat=40.735383;
var mcduckslon=-74.002994;
// current location
var currentpositionlat=position.coords.latitude;
var currentpositionlon=position.coords.longitude;
// calculate the distance between current location and McDuck's location
var distance=getDistanceFromLatLonInMiles(mcduckslat, mcduckslon,currentpositionlat,
currentpositionlon);
// Displays the location using .innerHTML property and the lat & long coordinates
// for your current location
document.getElementById("geodisplay").innerHTML="Latitude: " + currentpositionlat +
"<br>Longitude: " + currentpositionlon;
}
// haversine distance formula
The rest omitted for brevity because it's shown in Book 5, Chapter 2.
The showLocation()
function performs the following tasks:
Calculates the distance in miles between those two points and assigns that distance to a variable called distance (Line 20 of the code).
The Haversine formula calculates the distance between two points on a sphere, in this case the earth, and the code is shown online but omitted here for brevity.
With some of the code already written, and with research in the previous chapter, follow these steps to insert the code:
button
code below with onclick
attribute calling the getLocation()
function after line 8 in the HTML file.
<button onclick="getLocation()">McDuck's Check-in</button>
After you insert this code, press the button. If your location settings are enabled and you inserted the code properly, you will see a dialog box asking for your permission to share your computer’s location. As shown in Figure 3-2, look at the top of your browser window and click Allow.
Update lines 12 and 13 in the JavaScript file with the latitude and longitude of the restaurant near you serving as the McDuck’s store.
After you have updated the location, make sure to change the comment in line 10 to reflect the address of your restaurant (instead of my apartment).
Add an alert that displays the distance between your location and the restaurant.
The distance
variable stores the miles from your current location to the restaurant. Make a rough estimate — or use a map for greater precision — of your current distance from the restaurant you picked. Then using an alert, show the distance by inserting this code below in line 23.
alert(distance);
If the distance in the alert is larger or smaller than you expected, you likely entered in incorrect values for the latitude or longitude. If the distance matches your estimate, insert two slashes ("//") before the alert and comment it out.
Write an if-else statement on line 26 to show an alert if you are within your threshold distance to the restaurant.
My code, based on a half-mile threshold distance, is displayed below — yours may vary depending on your alert text and threshold distance. (See Figure 3-3.)
if (distance < 0.5) {
alert("You get a free burger");
}
else {
alert("Thanks for checking in!");
}
When your app logic is working, you can change alert("You get a free burger");
to an actual picture of a coupon or burger. To do so, replace the entire line the alert is on with the following code:
document.getElementById("effect").innerHTML="<img
src'http://www.image.com/image.jpg'>";
Replace the URL after src
and within the single quotes to your own image URL. Be sure to keep the double quotation marks after the first equal sign and before the semicolon, and the single quotation marks after the second equal sign and before the right angle bracket.
(Optional) When the app is working, change the text colors and insert background images to make the app look more professional.
Use hex-values or color names, as discussed in Book 3, Chapter 3, to change the text and background colors. Additionally, you can insert a background image, as you did in the Codecademy About You exercise, using the following code (see Figure 3-4):
background-image: url("http://www.image.com/image.jpg");
When coding your app, you will almost inevitably write code that does not behave as you intended. HTML and CSS are relatively forgiving, with the browser even going so far as to insert tags so the page renders properly. However, JavaScript isn’t so forgiving, and the smallest error, such as a missing quotation mark, can cause the page to not render properly.
Errors in web applications can consist of syntax errors, logic errors, and display errors. Given that we worked through the logic together, the most likely culprit causing errors in your code will be syntax related. Here are some common errors to check when debugging your code:
Keep these errors in mind when debugging — they may not solve all your problems, but they should solve many of them. If you have tried the steps above and still cannot debug your code, tweet me at @nikhilgabraham
and include the #codingFD
hashtag and your codepen.io
URL in your tweet.