How JavaScript & mapping works

There are a lot of ways to learn JavaScript on the web. You can use specific guides like Codecademy or Eloquent JavaScript. Or you can make maps.

In this guide, we’ll introduce you to JavaScript basics and how you can use them when building a map with Mapbox.js.

JavaScript basics

Variables

If you’re familiar with JavaScript, you’ve come across variables. In programming languages, they’re names you give to things.

var myName = 'Tom';

After you name something with a variable you can modify it by that name and send it around to different functions.

var myShoutingName = myName.toUpperCase();

Now myName is equal to 'Tom' but myShoutingName is 'TOM'.

Objects

Here’s an example of some basic data assigned to different variables.

var dogName = 'Barky';
var dogAge = 5;
var dogIsAGirl = true;

Objects are like buckets of different values that should be grouped together. Instead of three separate variables about a dog named Barky they can be stored as one object.

var dog = {
  name: 'Barky',
  age: 5,
  girl: true
};

You can now access parts of this dog object or edit it.

dog.name; // Barky
dog.name = 'Yelpy';
dog.name; // Yelpy

Classes

Classes are ways to make the same kind of object more than once. For instance, if you have ten dogs, you might grow tired of typing so much, so you can create a class:

function Dog(name, age, girl) {
  this.name = name;
  this.age = age;
  this.girl = girl;
}

// get a new dog
var newDog = new Dog('Professor Barksalot', 1, false);

Classes also establish a convention in your code. If something is made with Dog you know there’s a .name property you can access.

The `new` operator

Traditionally, when you create a JavaScript class like we did above, you would use the new operator making Dog a constructor. The new operator does a couple things. It creates a new object that inherits methods found in Dog.prototype. Also the this keyword is bound to the newly created object, newDog. Here’s an example with the native Date() function.

var time = new Date();

Date is the constructor and time is a newly created object that inherits all the methods found in Date().

Remembering to use the new operator is important, but it’s also confusing and annoying which is why many JavaScript libraries implement an auto-new function automatically so you don’t need to think about it. In the case of Mapbox.js and Leaflet, any class that starts with a lowercase letter is initialized with auto-new, whereas any capital letter is a traditional class.

// a place, created with auto-new
var place = L.latLng(0, 0);

// another place, with a traditional constructor
var place2 = new L.LatLng(0, 0);

Mapbox.js and JavaScript

Here’s a simple initialization of a map in Mapbox.js.

var map = L.mapbox.map('map');

map is a variable we are assigning to the class L.mapbox.map. It’s an automated way of saying, Make me an object with all the things I need in a map. map is now an object containing methods like map.setZoom() to do useful things.

Callbacks

Callbacks are built into code to deal with timing. Some parts of your code might need to run after something has happened like a file being downloaded or someone clicking on the page. To ensure your code didn’t run before something happened, callbacks are used.

One of the simplest examples of a callback is window.setTimeout a built-in function that lets you set a timer for something to happen. It takes two arguments: a function, and the number of milliseconds that should pass to execute the function.

window.setTimeout(function() {
  alert('hi');
}, 1000);

When 1,000 milliseconds has passed, the page calls the alert function. This is an important detail to how callbacks work: they are functions that you don’t call directly, but are called for you when the time is right.

You’ll see callbacks everywhere in maps. Let’s say you want to run something after a user clicks on a map.

map.on('click', function() {
  alert('I was clicked!');
});

The function containing alert is called only after map has been clicked.

AJAX & downloads

Callbacks are important to AJAX, a technique for downloading resources on the fly in order to show content. When you create a new L.mapbox.featureLayer, you might be tempted to do this:

// get the features from mapid `username.mapid`
var featureLayer = L.mapbox.featureLayer('username.mapid');

// Print out the GeoJSON from featureLayer
console.log(featureLayer.getGeoJSON());

But you’ll notice there’s no content when getGeoJSON is called. The reason is JavaScript needs to download this layer and doesn’t wait until L.mapbox.featureLayer('foo.bar'); has completed. It says, “start downloading this” and then moves on. So to circumvent this, listen for an event and execute a callback.

var featureLayer = L.mapbox.featureLayer('foo.bar');

featureLayer.on('ready', function() {
  console.log(featureLayer.getGeoJSON());
});

The L.mapbox.featureLayer class has a callback that fires as soon as the layer has been downloaded. If you wait for this callback, then you know that .getGeoJSON() and other functions that rely on this layer will work as expected.

JSON & GeoJSON

You’ll likely see the terms JSON & GeoJSON when you hear about map data: GeoJSON is a popular format for storing features that make up map overlays.

GeoJSON follows the same format as JSON. JSON, or JavaScript Object Notation, is a way of storing data in standalone files that are easily readable by JavaScript. Let’s say you have an object like this:

var myBird = {
  age: 10,
  name: 'Smokey'
};

JSON closely resembles this object structure but its more strict. There are no variables or comments allowed and " must be used to wrap strings.

{
  "age": 10,
  "name": "Smokey"
}

Here’s an example of some simple GeoJSON:

{
  "type": "Point",
  "coordinates": [-77, 38]
}

That’s a point at longitude=-77, latitude=38.

The important point to JSON is that once you bring it into JavaScript, it’s the same as any other object in JavaScript: you can change it, or use it as a variable in any function.

featureLayer.setGeoJSON(geoJsonData);

The code is really saying it expects a JavaScript object that’s formatted like GeoJSON. It doesn’t care about how it got there.

Next steps

Nice work! You now know the basics of JavaScript and you’re ready to make something awesome with Mapbox.js. We recommend checking out the Extending with Mapbox.js guide.

Whatever you build, we want to see it! Tweet your projects @mapbox.

Additional questions? Ask our support team or learn more about How Mapbox Works.