Viewing an older version of MapBox.js. Check out v1.5.0 for the latest.

Reading this Documentation

MapBox.js is built on top of Leaflet and should be read in conjunction with the Leaflet API reference.

The documentation is organized by methods. Each method is shown with potential arguments along with it's type and description in a table. When the API has a Javascript constructor function that returns an object, the constructor is documented with its full name and the methods on the object are named with just the type of the object. For instance, L.mapbox.markerLayer documents a function that returns a layer for markers. The methods on that object are then documented as markerLayer.setFilter, markerLayer.getGeoJSON, and so on.

To use this API, you'll need to understand basic Javascript and mapping concepts. If you'd like to learn Javascript, start with an interactive course, or book. If you'd like to learn more about maps, we've provided a helpful article explaining how web maps work.

The `ready` event

MapBox.js is asynchronous - when you create a layer like L.mapbox.tileLayer('examples.map-9ijuk24y'), the layer doesn't immediately know which tiles to load and its attribution information. Instead, it loads the information in an AJAX call.

For most things you'll write, this isn't a problem, since MapBox.js does a good job of handling these on-the-fly updates. If you're writing code that needs to know when layers and other dynamically-loaded objects are ready, you can use the ready event to listen for their ready state. For instance:

  var layer = L.mapbox.tileLayer('examples.map-9ijuk24y');
  layer.on('ready', function() {
      // the layer has been fully loaded now, and you can
      // call .getTileJSON and investigate its properties
  });
  

Similarly, dynamically-loaded objects produce an `error` event if something goes wrong:

  var layer = L.mapbox.tileLayer('examples.map-9ijuk24y');
  layer.on('error', function(err) { // Handle error });
  

The Map

The map is, of course, the central element of most mapping sites. In the MapBox JavaScript API, the map object manages a set of layers, stores and displays zoom levels and centerpoints, and accepts a set of UI controls to which you can add your own finishing touches.

Technically speaking, maps are based on Modest Maps, so the full Modest Maps API is available to power-users.

mapbox.map(element [, layers])

Create a map on the current page.

Arguments:

  • element must be the id of an element on the page, or an element itself. Typically maps are created within <div> elements
  • layers can be a layer created with mapbox.layer(), an array of such layers, or omitted

Returns a map object, which has the following methods:

map.smooth(value)

Enable or disable inertial panning on maps. By default, maps smoothly pan and zoom with inertia.

Arguments:

  • value must be true or false to set whether the map uses inertia.

Returns the map object.

Example:

map.smooth(false); // disable inertial panning

map.center(centerpoint [, animate])

Center the map on a geographical location, or get its current center.

Arguments:

  • centerpoint can be an object with lat and lon values, like { lat: 10, lon: -88 }, or ommitted to get the map's current location
  • animate can be true to animate the map's movement, or omitted to move immediately

Returns the map object if arguments are given, the map's center location (in the same form as specified in centerpoint) otherwise.

map.zoom(zoom [, animate])

Set the map's zoom level, or get its current zoom level.

Arguments:

  • zoom can be zoom level in the range supported by the map's layers (an integer from 0-20, typically), or omitted to get the current zoom level..
  • animate can be true to animate the map's movement, or omitted to move immediately.

Returns the map object if arguments are given, the map's current zoom level otherwise.

Example:

map.zoom(10, true);

map.centerzoom(center, zoom [, animate])

Set the map's zoom level and centerpoint simultaneously. Especially with the third argument, animate, set to true, this allows for a better animation effect.

Arguments:

  • centerpoint can be an object with lat and lon values, like { lat: 10, lon: -88 }
  • zoom must be zoom level in the range supported by the map's layers (an integer from 0-20, typically)
  • animate can be true to animate the map's movement, or omitted to move immediately.

Returns the map object.

Example:

map.centerzoom({ lat: 10, lon: -88 }, 5);

map.setPanLimits(locations)

Set the map's panning limits.

Arguments:

  • locations must be either an instance of MM.Extent or an array of locations in the order north, west, south, east.

Returns the map object.

map.refresh()

Refreshes map.ui and map.interaction to reflect any layer changes.

map.addTileLayer(layer)

Adds a tile layer to the map, below any marker layers to prevent them from being covered up.

map.ease()

An instance of easey initialized with the map.

Example:

map.ease.location({ lat: 10, lon: -88 }).zoom(5).optimal();

map.ui()

An instance of mapbox.ui attached to the map for convenience.

map.interaction()

An instance of mapbox.interaction attached to map for convenience.

Loading Utilities

To load information about a certain map you've created on MapBox, we provide mapbox.load and mapbox.auto, which pull the TileJSON file from a server and auto-instantiate many of its features.

mapbox.load(url, callback)

This loads the information about a map on MapBox Hosting. The first argument can either be a full URL to a TileJSON file, like http://a.tiles.mapbox.com/v3/tmcw.map-hehqnmda.jsonp, or a bare id, like tmcw.map-hehqnmda, which will get expanded to the former.

After pulling the information from MapBox, it calls the function specified at the second argument with an object with map parts you can combine for yourself:

{
  zoom: ZOOM_LEVEL,
  center: CENTER,

  // like you could create with mapbox.layer()
  layer: TILE_LAYER,

  // if present, like you would create with mapbox.markers()
  markers: MARKERS_LAYER 
}

mapbox.auto(element, url [, callback])

Automatically load and create a map with sensible defaults.

Arguments:

  • element must be the id of an element on the page, or an element itself. Typically maps are created within <div> elements
  • url must be a TileJSON URL, the id of a MapBox map, multiple IDs and URLs in an array.
  • callback if specified, receives the map as its first argument, and the same object as mapbox.load as the second argument. It is called after all resources have been loaded and the map is complete.

Returns undefined: this is an asynchronous function without a useful return value.

Example:

<div id='map' style='width:500px;height:400px;'></div>
<script>
mapbox.auto('map', 'http://a.tiles.mapbox.com/v3/tmcw.map-hehqnmda.jsonp');
</script>

MapBox Layer

mapbox.layer is a fast way to add layers to your map without having to deal with complex configuration.

mapbox.layer()

You can add a tiled layer to your map with mapbox.layer(), a simple interface to layers from MapBox Hosting and elsewhere.

Returns a layer object, which has the following methods:

layer.id(id, callback)

Get or set the layer ID, which corresponds to a MapBox map.

Arguments:

  • id can be the id of a MapBox Hosting map, or omitted to get the current id value. This also calls .named() setting the name to be the same as the id - call named() to reset it. For instance, if you were trying to add the map at https://tiles.mapbox.com/tmcw/map/map-hehqnmda, you could create this layer like so:
  • callback, if provided, is called after the layer has been asynchronously loaded from MapBox. It is called with on argument, the layer object.

Returns the layer object if arguments are given, the layer's id otherwise.

Example:

var layer = mapbox.layer().id('map-hehqnmda');

layer.named([name])

Get or set the name of the layer, as referred to by the map.

Arguments:

  • name can be a new name to call this layer

Returns the layer object if arguments are given, the layer's name otherwise.

layer.url([url, callback])

Pull a layer from a server besides MapBox Hosting that supports TileJSON, like a self-hosted TileStream.

Arguments:

  • url can be a string value that is a fully-formed URL, or omitted to get the URL from which this layer was sourced.
  • callback, if provided, is called with one argument, the layer object, after the TileJSON information has been asynchronously loaded.

Returns the layer object if arguments are given, the pulled URL otherwise.

Example:

var layer = mapbox.layer().url('http://a.tiles.mapbox.com/v3/tmcw.map-hehqnmda.jsonp');

layer.tilejson([tilejson])

Set layer options directly from a TileJSON object.

Arguments:

  • tilejson must be a TileJSON object as a Javascript object.

Returns the layer object if arguments are given, the layer's TileJSON settings otherwise.

Map UI

The API provides a set of UI elements that can be freely mixed & matched, as well as styled beyond the default (provided in the mapbox.css stylesheet). Maps created with mapbox.map have an array of pre-initialized UI elements at .ui. All UI elements support the simple operations .add() and .remove() to add & remove them from the map.

.add()

Add the UI element to the map. Add the HTML elements that the UI element manages (if any) to the map element, and bind any events.

.remove()

Remove the UI element from the map. Removes the HTML elements from the map, if any, and removes listeners, if any.

map.ui.hash()

Add the map's changing position to the URL, making map locations linkable

map.ui.zoombox()

Add the ability to zoom into the map by shift-clicking and dragging a box, to which the map zooms

map.ui.zoomer()

Add zoom in and zoom out buttons to map

map.ui.attribution()

Add an element with attribution information to the map

map.ui.legend()

Add an element with legend information to map

map.ui.pointselector()

Allow simple location selection on the map: clicking without dragging will select a point, and notify listeners with the new list of points.

pointselector.addCallback(event, callback)

Adds a callback that is called on changes to the pointselector contents.

Arguments:

  • event is a string of the event you want to bind the callback to
  • callback is a funcion that is called on the event specified by event

Event should be a String which is one of the following:

  • change: whenever points are added or removed

Callback is a Function that is called with arguments depending on what event is bound:

  • drawn: the layer object
  • locations: a list of locations currently selected

Returns the pointselector

pointselector.removeCallback(event, callback)

Remove a callback bound by .addCallback(event, callback).

Arguments:

  • event is a string of the event you want to bind the callback to This must be the same string that was given in addCallback

  • callback is a funcion that is called on the event specified by event. This must be the same function as was given in addCallback.

Returns the pointselector

map.ui.boxselector()

Allow extents to be selected on the map.

boxselector.addCallback(event, callback)

Adds a callback that is called on changes to the boxselector contents.

Arguments:

  • event is a string of the event you want to bind the callback to
  • callback is a funcion that is called on the event specified by event

Event should be a String which is one of the following:

  • change: whenever an extent is selected

Callback is a Function that is called with arguments depending on what event is bound:

  • drawn: the layer object
  • extent: the currently selected extent

Returns the boxselector

boxselector.removeCallback(event, callback)

Remove a callback bound by .addCallback(event, callback).

Arguments:

  • event is a string of the event you want to bind the callback to This must be the same string that was given in addCallback

  • callback is a funcion that is called on the event specified by event. This must be the same function as was given in addCallback.

Returns the boxselector

Interaction

Interaction is what we call interactive parts of maps that are created with the powerful tooltips & regions system in TileMill. Under the hood, it's powered by the open UTFGrid specification.

mapbox.interaction()

Create an interaction control which will find and present interactive regions of the map.

Returns a new interaction control.

interaction.map(map)

Set the map to add interaction for.

interaction.auto()

Enable default settings - animated tooltips - for interaction with the map. This internally calls .refresh() to set the interactivity for the top layer.

Returns the interaction control

Example:

var interaction = mapbox.interaction()
    .map(map)
    .auto();

interaction.refresh()

Refresh interactivity control to reflect any layer changes. If auto has not been called, this function will not change anything.

Returns the interaction control

The Markers Layer

mapbox.markers() is a markers library that makes it easier to add HTML elements on top of maps in geographical locations and interact with them. Internally, markers are stored as GeoJSON objects, though interfaces through CSV and simple Javascript are provided.

mapbox.markers()

mapbox.markers() is the singular entry point to this library - it creates a new layer into which markers can be placed and which can be added to a Modest Maps map with .addLayer()

markers.named([name])

Set the name of this markers layer. The default name for a markers layer is 'markers'

Arguments:

  • name if given, must be a string.

Returns the layer object if a new name is provided, otherwise the layer's existing name if it is omitted.

markers.factory([factoryfunction])

Define a new factory function, and if the layer already has points added to it, re-render them with the new factory. Factory functions are what turn GeoJSON feature objects into HTML elements on the map. Due to the way that markers.js allows multiple layers of interactivity, factories that want their elements to be interactive must either set .style.pointerEvents = 'all' on them via Javascript, or have an equivalent CSS rule with pointer-events: all that affects the elements.

Arguments:

  • factoryfunction should be a function that takes a GeoJSON feature object and returns an HTML element, or omitted to get the current value.

Returns the layer object if a new factory function is provided, otherwise the layer's existing factory function

markers.features([features])

This is the central function for setting the contents of a markers layer: it runs the provided features through the filter function and then through the factory function to create elements for the map. If the layer already has features, they are replaced with the new features. An empty array will clear the layer of all features.

Arguments:

Returns the layer object if a new array of features is provided, otherwise the layer's features

markers.sort([sortfunction])

Markers are typically sorted in the DOM in order for them to correctly visually overlap. By default, this is a function that sorts markers by latitude value - geometry.coordinates[1].

Arguments:

  • sortfunction can be a function that takes two GeoJSON feature objects and returns a number indicating sorting direction - fulfilling the Array.sort interface, or omitted to get the current value.

**Returns the layer object if a new function is specified, otherwise the current function used to sort.

Example: // The default sorting function is: layer.sort(function(a, b) { return b.geometry.coordinates[1] - a.geometry.coordinates[1]; });

markers.filter([filterfunction])

Set the layer's filter function and refilter features. Markers can also be filtered before appearing on the map. This is a purely presentational filter - the underlying features, which are accessed by .features(), are unaffected. Setting a new filter can therefore cause points to be displayed which were previously hidden.

Arguments:

  • filterfunction can be a function that takes a GeoJSON feature object and returns true to allow it to be displayed or false to hide it, or omitted to get the current value

**Returns the layer object if a new function is specified, otherwise the current function used to filter.

Example:

// The default filter function is:
layer.filter(function() { return true; });

markers.id([idfunction])

Set the id getter for this layer. The id getter is a funcion that takes a GeoJSON feature and returns a unique id for that feature. If this is provided, the layer can optimize repeated calls to .features() for animation purposes, since updated markers will not be recreated, only modified.

Arguments:

  • idfunction must be a function that takes a GeoJSON object and returns a unique ID for it that does not change for the same features on repeated calls

Returns the layer object if a new function is specified, otherwise the current function used to get ids.

Example:

// The default id function is:
var _seq = 0;
layer.id(function() { return ++_seq; });
// Thus this function always returns a new id for any feature. If you had
// features that do have an id attribute, a function would look like
layer.id(function(f) { return f.properties.id; });

markers.url(url [, callback])

Loading features from a remote GeoJSON file into the layer.

Arguments:

  • url should be a URL to a GeoJSON file on a server. If the server is remote, the GeoJSON file must be served with a .geojsonp extension and respond to the JSONP callback grid.
  • callback, if provided, is optional and should be a callback that is called after the request finishes, with the error (if encountered), features array (if any) and the layer instance as arguments. If an error is encountered, .url() will not call .features(), since this would likely clear the features array.

markers.csv(csvstring)

Convert a string of CSV data into GeoJSON and set layer to show it as features. If it can find features in the CSV file, the .features() of the layer are set to them - otherwise it will throw an error about not finding headers.

Arguments:

  • csvstring must be a string of CSV data. This method returns the markers layer. The CSV file must include columns beginning with lat and lon in any case (Latitude, latitude, lat are acceptable).

Returns the markers layer

markers.extent()

Get the extent of all of the features provided.

Returns an array of two { lat: 23, lon: 32 } objects compatible with Modest Maps's extent() call. If there are no features, the extent is set to Infinity in all directions, and if there is one feature, the extent is set to its point exactly.

markers.addCallback(event, callback)

Adds a callback that is called on certain events by this layer. These are primarily used by mmg_interaction, but otherwise useful to support more advanced bindings on mmg layers that are bound at times when the mmg object may not be added to a map - like binding to the map's panned event to clear tooltips.

Arguments:

  • event is a string of the event you want to bind the callback to
  • callback is a funcion that is called on the event specified by event

Event should be a String which is one of the following:

  • drawn: whenever markers are drawn - which includes any map movement
  • markeradded: when markers are added anew

Callback is a Function that is called with arguments depending on what event is bound:

  • drawn: the layer object
  • markeradded: the new marker

Returns the markers layer

markers.removeCallback(event, callback)

Remove a callback bound by .addCallback(event, callback).

Arguments:

  • event is a string of the event you want to bind the callback to This must be the same string that was given in addCallback

  • callback is a funcion that is called on the event specified by event. This must be the same function as was given in addCallback.

Returns the markers layer

mapbox.markers.interaction(markerslayer)

Classic interaction, hovering and/or clicking markers and seeing their details, is supported by marker_interaction and customizable through its methods. This supports both mouse & touch input.

Adds tooltips to your markers, for when a user hovers over or taps the features.

Arguments:

  • markerslayer must be a markers layer.

Returns an interaction instance which provides methods for customizing how the layer behaves.

interaction.hide_on_move([value])

Determines whether tooltips are hidden when the map is moved. The single argument should be true or false or not given in order to retrieve the current value.

Arguments:

  • value must be true or false to activate or deactivate the mode

Returns the interaction instance.

interaction.exclusive([value])

Determines whether a single popup should be open at a time, or unlimited. The single argument should be true or false or not given in order to retrieve the current value.

Arguments:

  • value must be true or false to activate or deactivate the mode

Returns the interaction instance.

interaction.formatter([formatterfunction])

Set or get the formatter function, that decides how data goes from being in a feature's properties to the HTML inside of a tooltip. This is a getter setter that takes a Function as its argument.

Arguments:

  • formatterfunction: a new function that takes GeoJSON features as input and returns HTML suitable for tooltips, or omitted to get the current value.

Returns the interaction instance if a new formatter function is provided, otherwise the current formatter function

Example:

// The default formatter function
interaction.formatter(function(feature) {
    var o = '', props = feature.properties;
    if (props.title) {
        o += '<h1 class="mmg-title">' + props.title + '</h1>';
    }
    if (props.description) {
        o += '<div class="mmg-description">' + props.description + '</div>';
    }
    if (typeof html_sanitize !== undefined) {
        o = html_sanitize(o,
            function(url) {
                if (/^(https?:\/\/|data:image)/.test(url)) return url;
            },
            function(x) { return x; });
    }
    return o;
});

Easing

Easing is moving from one point or zoom to another in a fluid motion, instead of just 'popping' from place to place. It's useful for map-based storytelling, since users get a better idea of geographical distance.

var ease = mapbox.ease()

Returns an easey object, which has the following methods:

ease.from(coord)

Set the starting coordinate for the easing. You don't usually need to call this, because easings default to the current coordinate.

Arguments:

  • coord is an instance of MM.Coordinate representing the starting coordinate for the easing.

Returns the easey object.

ease.to(coord)

Set the destination coordinate for the easing.

Arguments:

  • coord is an instance of MM.Coordinate representing the destination coordinate for the easing.

Since easey deals exclusively in Coordinates, the reference for converting between points, locations, and coordinates in Modest Maps is essential reading.

Returns the easey object.

ease.zoom(level)

Set the zoom level of the to coordinate that easey is easing to.

Arguments:

  • level is a number representing the zoom level

Returns the easey object.

ease.t(value)

Set the map to a specific point in the easing.

Arguments:

  • value is a float between 0 and 1, where 0 is from and 1 is to.

Returns the easey object.

ease.future(parts)

Get the future of an easing transition, given a number of parts for it to be divided over. This is a convenience function for calling easey.t() a bunch of times.

Arguments:

  • parts is an positive integer representing the number of parts to divide the easing into.

Returns an array of MM.Coordinate objects representing each in-between location.

ease.easing(name)

Set the easing curve - this defines how quickly the transition gets to its end and whether it speeds up or slows down near the beginning and end.

Arguments:

  • name is the string name of the easing to use. Current options are:
    • 'easeIn'
    • 'easeOut'
    • 'easeInOut'
    • 'linear'

Returns the easey object.

ease.path(pathname)

Set the type of path - the type of interpolation between points.

Arguments:

  • pathname is a string name of the path to use. Current options are:
    • screen: a 'straight line' path from place to place - in the Mercator projection, this is a rhumb line
    • about: the default path for a double-click zoom: this keeps a single coordinate in the same screen pixel over the zoom transition

Returns the easey object.

ease.run([time [, callback])

Start an animated ease. Both parameters are optional.

Arguments:

  • time is an integer representing the duration of the easing in milliseconds (default is 1000).
  • callback is a Javascript function that is called when the map has reached its destination.

Returns the easey object.

var isRunning = ease.running()

Returns true or false depending on whether easey is currently animating the map.

ease.stop()

Abort the currently running animation.

Returns the easey object.

The code and documentation to mapbox.js is hosted on GitHub where you can contribute changes and improvements.