Skip to content

FETCH and THEN

Time to dive back into scary JavaScript waters! Before doing so, let’s just make sure we are warmed-up for our swim!

Back to JavaScript variables again!

Need a variable refresher?

Revisiting more variable definitions

What we really need to understand about variables is that they act like boxes where you can store or take information out of. - const acts like a locked safe that will not let you put anything into it after you define it - let is like a regular box. - var is VARy problematic because it can be both locked and unlocked

Here are some of the types in JavaScript:

//number
let box1 = 5;
let box2 = 5.0;

//string
let box3 = 'five';
let box4 = "five";

// string literal, uses backticks and ${variable} to bring in another variable
let box5 = `this is from box #4: ${box4}`;

// array, which is a list of things
let box6 = [1,2,3,4,5]; 

// Object, stores variables together, can be of different types!
let box7 = {"number": 'five', "value":5};

// boolean (true or false)
let box8 = true;

// null value
let emptyBox;

Remember, to declare a variable or give it a value you must use the = symbol, like so:

let my_variable = "exist!";

Anatomy of a variable declaration

  • let is the keyword declaration of a variable
  • my_variable is the variable’s name
  • "exist!" is the value for this variable
  • ; defines the end of a line in JavaScript

```

JavaScript Warm-up: Using Variables

Instead of hard coding the values, we can use variables to store the values. For example, instead of writing:

const map = L.map('the_map').setView([34.0709,-118.444], 5);

We can write:

// declare the variables
let mapCenter = [34.0709,-118.444]
const zoom = 5

// declare the map and use the variables above
const map = L.map('the_map').setView(mapCenter, zoom);

This is a little more work, but it is much easier to change the values later. For example, if we wanted to change the map center, we can just change the value of mapCenter instead of having to change the value in multiple places.

Finished warm-up code

js/init.js
// declare the variables
let mapCenter = [34.0709,-118.444]
const zoom = 5

// declare the map and use the variables above
const map = L.map('the_map').setView(mapCenter, zoom);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

addMarker(37,-122,'home','home land!')
addMarker(32,-118,'work','where i work land!')
addMarker(39,-119,'location 1','random location')
addMarker(36,-120,'location 2','another random location')

// create a function to add markers
function addMarker(lat,lng,title,message){
    console.log(message)
    L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`)
    return message
}

JavaScript Objects - Boxing-up our variables

An object is a unique variable that can store many other variables! Think of it as a big box where many other Lego pieces or even other boxes can be put inside!

let myJavaScriptObject = {"key_name": "value", "key_2_name":"value"}

Your object can look like this too:

    let myJavaScriptObject = {
        "key_name": "value", 
        "key_2_name":"value"
        };
Wait! Didn’t we see this somewhere?

Yep! It was in the GeoJSON we created!

The meaning behind GeoJSON

GeoJSON actually stands for “geographic” JavaScript Object Notation! 🤯

In a JavaScript object, each value has a key and a value.

The : symbol seperates the key from the value, like this:

let myObject = {"key":"value"};
  • Everything in an object is contained within the curly braces {}
  • Anything to left of the : is the key
  • Anything to right of the : is the value
  • New key-value pairs are separated by a comma, ,
  • ⚠ Warning ⚠! Never end an object with a ,!!!!

Accessing an object’s property

To access an object’s properties we use the . notation.

For example, myObject.key will return the value, which in this case is.. value!

No 🚀 spaces 🪐 in variable names!

You cannot use spaces in variable definitions like let my map;, so stick with camelCase or snake_case when naming varibles with multiple words. When defining keys in objects, you can use spaces, but it is not recommended.

If you do encounter a key with a space in it, like, let anObject = "my annoying key": "is this", you cannot use the . syntax to access it you must use this alternative method: anObject["my annoying key"]

⚽In-class Exercise #1 - Variables and console.log

Tasks

  1. Re-copy this week’s lab template with index.html and init.js
  2. Replace the hard coded values of const map = L.map('the_map').setView(mapCenter, zoomLevel); with an object.
  3. Get the object to show up in the console.

Reminder: Working with our Dev Console

In VS Code, start Live Server by clicking Go Live.

After Firefox runs, open the Console:

  • You can either right click anywhere on a page with the mouse and clicking on Inspect or press F12 on the keyboard.

Remember to think of the Console as the Command Line/Terminal for your browser.

Answer

Your code should look like the following:

    let mapOptions = {'center': [34.0709,-118.444],'zoom':5}
    const map = L.map('the_map').setView(mapOptions.center, mapOptions.zoom);
    console.log(mapOptions)
  1. In the console, type in mapOptions (or whatever you chose to name your object) then press Enter.

  2. You should see your JavaScript object, mapOptions!

Reflection

Think about the benefits of having variables in an object, is it easier to read for you? Harder?

Knowing how to check the console will help us test our JavaScript code and even run functions and methods without leaving the browser!

Finished Exercise #1 code

Make sure your code looks like the following before moving on:

js/init.js
let mapOptions = {'center': [34.0709,-118.444],'zoom':5}

// declare the map and use mapOptions
const map = L.map('the_map').setView(mapOptions.center, mapOptions.zoom);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

addMarker(37,-122,'home','home land!')
addMarker(32,-118,'work','where i work land!')
addMarker(39,-119,'location 1','random location')
addMarker(36,-120,'location 2','another random location')

// create a function to add markers
function addMarker(lat,lng,title,message){
    console.log(message)
    L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`)
    return message
}

A method to my madness?!

With that refresher about variables and practice with objects in mind, do you remember how our functions in last week’s lab took a variable and did something to it?

Variables have built-in functions called methods!!!

For example, string-type variables have methods for changing the string, like making all the letters UPPERCASE or splitting a character based on a . To access a method, you use the . after the variable has been declared as that type.

Calling methods for what they are ()

Since methods are functions, you must call them in the same way with the () at the end. This is because some methods have parameters you can fill in.

A helping console hand!

You can check what methods are available right in Firefox’s web developer console! Most modern web browsers have this feature as well.

To give this a try, copy and paste this right into your web browser and see what happens!

let myString = "hi, this is a test string"
let divideBySpace = myString.split(" ")
console.log(divideBySpace) 
Did you get this response?

result: Array(6) [ "hi,", "this", "is", "a", "test", "string" ]

If you did, yay! This is an array (list), of 6 strings!

⚽In-class Exercise #2 - What other methods are available?

As with all languages, learning to look-up things is important to expand what you can say and do! The following is a table of where you can find some methods:

Location Type
MDN Strings
W3 Strings
W3 Numbers
W3 Arrays
W3 Objects

Tasks

  1. Visit one of the links above or search online to find other methods.
  2. Get the result to display in your console.
  3. Bonus: read the next section try to chain multiple methods together.
Answer

Here is an example of an uppercase method:

let myString = "hi, this is a test string"
let divideBySpace = myString.toUpperCase()
console.log(divideBySpace) 

Result:

"HI, THIS IS A TEST STRING"

Method chaining

In JavaScript whenever you see a . after a parenthesis(),it means you are chaining a function to follow it.

For example:

let myString = "hi this is a test string"
let divideBySpace = myString.toUpperCase().split(" ")
console.log(divideBySpace)

The output should look a little bit different than last time thanks to the toUpperCase() method!

Output

Array(6) [ "HI", "THIS", "IS", "A", "TEST", "STRING" ]

Time to fetch and then do something

To access data, we will use the JavaScript Fetch API to fetch our GeoJSON file and then add it to our map.

When we access the GeoJSON file with the Fetch API we then get many methods to use with it.

A fetch looks like this:

fetch("map.geojson")

Wait! No variable declaration?! 😢

Why do you think so?

Answer

The fetch API is actually a built-in function for JavaScript, much like console.log()!

Good? Let’s carry on then!

fetch actually does nothing by itself! It needs to do something with the data. Thus, fetch is almost always used together with the then method as follows:

fetch("map.geojson") //(1)! 
    .then(function aGenericDataFunctionName(data){//(2)!
        return data.json()//(3)!
    })
    .then(function anotherGenericDataFunctionName(data){ //(4)!
        // Basic Leaflet method to add GeoJSON data
        L.geoJSON(data).addTo(map)//(5)!
    });
  1. map.geojson is location of the GeoJSON file relative to our file. If you moved the file to a subdirectory called data, then you would have to make this data/map.geojson.
  2. Here is our first chain, we are trying to fetch our geojson file. We will call a generic function in here.
  3. For the next step we need a json, so we return the value as a json with the .json() method!
  4. This is the next then i.e. our second chain!
  5. This calls L.geoJSON() and adds our data to the map.

Anoynmous functions

Since our .then is a one-time call, it does not need named functions as a part of it!

So we can make our function anoymous by removing the name part of it.

Here’s how the simpler fetch-then should look:

fetch("map.geojson")
    .then(function (data){
        return data.json()
    })
    .then(function (data){
        // Basic Leaflet method to add GeoJSON data
        L.geoJSON(data).addTo(map)
    });

Looks much better, right? Well… We can shorten it even more!!!

WHAT IS THIS => 😡?!!!

The => is a shortcut to define an anoynmous function and is called an arrow-function!

Here is how it looks in practice:

fetch("map.geojson") //(1)! 
    .then(response => { //(2)! 
        return response.json();
    })
    .then(data =>{ //(3)!
        // Basic Leaflet method to add GeoJSON data
        L.geoJSON(data).addTo(map)//(4)!
    });
  1. map.geojson is location of the GeoJSON file relative to our file. If you moved the file to a subdirectory called data, then you would have to make this data/map.geojson.
  2. Here is our first chain, we are trying to fetch our geojson file.
  3. This is our next chain, we are trying to add it to our map!
  4. The addTo(map) is similar to our marker.addTo(map) function call!

The map should now have a blue tint over it and you cannot interact with it. Not really useful.

Going forward we will use the arrow-function because it is shorter, but if you want to use the other methods, feel free to.

🏁Checkpoint

Before moving on, check to see if JavaScript code looks like the following:

js/init.js
// declare variables
let mapOptions = {'center': [34.0709,-118.444],'zoom':5}

// use the variables
const map = L.map('the_map').setView(mapOptions.center, mapOptions.zoom);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

// create a function to add markers
function addMarker(lat,lng,title,message){
    console.log(message)
    L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`)
    return message
}

fetch("map.geojson")
    .then(response => {
        return response.json();
    })
    .then(data =>{
        // Basic Leaflet method to add GeoJSON data
        L.geoJSON(data).addTo(map)
    });