Create and automatically configure a map with layers, markers, and interactivity.
Extends: L.Map
Options | Value | Description |
---|---|---|
element (required) | string | Must be the id of an element, or a DOM element reference. |
id or url or tilejson | string if id or url object if tilejson | url can be |
options | object | If provided, it is the same options as provided to L.Map with the following additions:
|
Example:
// map refers to a <div> element with the ID map
// mapbox.streets is the ID of a map on Mapbox.com
var map = L.mapbox.map('map', 'mapbox.streets');
// map refers to a <div> element with the ID map
// This map will have no layers initially
var map = L.mapbox.map('map');
Returns: a map object
Class: L.mapbox.Map
Returns this map's TileJSON object which determines its tile source, zoom bounds and other metadata.
Returns: the TileJSON object
You can add a tiled layer to your map with L.mapbox.tileLayer()
, a simple
interface to layers from Mapbox and elsewhere.
Extends: L.TileLayer
Options | Value | Description |
---|---|---|
id or url or tilejson (required) | string if id or url object if tilejson | Value must be
|
options | object | The second argument is optional. If provided, it is the same options as provided to L.TileLayer , with the following addition:
|
Example:
// the second argument is optional
var layer = L.mapbox.tileLayer('mapbox.streets');
// you can also provide a full url to a TileJSON resource
var layer = L.mapbox.tileLayer('{{site.tileApi}}/v3/mapbox.dark.json');
Returns a L.mapbox.tileLayer
object.
Class: L.mapbox.TileLayer
Returns this layer's TileJSON object which determines its tile source, zoom bounds and other metadata.
Example:
var layer = L.mapbox.tileLayer('mapbox.streets')
// since layers load asynchronously through AJAX, use the
// `.on` function to listen for them to be loaded before
// calling `getTileJSON()`
.on('ready', function() {
// get TileJSON data from the loaded layer
var TileJSON = layer.getTileJSON();
});
Returns: the TileJSON object
Set the image format of tiles in this layer. You can use lower-quality tiles in order to load maps faster
Options | Value | Description |
---|---|---|
format | string | string an image format. valid options are: 'png', 'png32', 'png64', 'png128', 'png256', 'jpg70', 'jpg80', 'jpg90' |
Example:
// Downsample tiles for faster loading times on slow
// internet connections
var layer = L.mapbox.tileLayer('mapbox.streets', {
format: 'jpg70'
});
Live example of .setFormat in use
Returns: the layer object
An L.mapbox.gridLayer
loads UTFGrid tiles of
interactivity into your map, which you can easily access with L.mapbox.gridControl
.
Options | Value | Description |
---|---|---|
id or url or tilejson (required) | string if id or url object if tilejson |
|
options | Object | The second argument is optional. If provided, it may include:
|
Example:
// the second argument is optional
var layer = L.mapbox.gridLayer('mapbox.light');
Returns a L.mapbox.gridLayer
object.
Class: L.mapbox.GridLayer
Bind an event handler to a given event on this L.mapbox.gridLayer
instance.
GridLayers expose a number of useful events that give you access to UTFGrid
data as the user interacts with the map.
Options | Value | Description |
---|---|---|
event (required) | string | the event name |
handler (required) | function | a callback function run every time that the event is fired |
context (optional) | object | the context of the handler function: this is the value of this when that function returns |
After binding an event with .on
, you can unbind it with .off
, with the
same argument structure.
The default events are:
click
: mouse has clicked while on a feature in UTFGrid. Event has{ latLng: location, data: featureData }
as its data.mouseover
: mouse has moved onto a new feature in UTFGrid. Event has{ latLng: location, data: featureData }
as its data.mousemove
: mouse has moved within a feature in UTFGrid. Event has{ latLng: location, data: featureData }
as its data.mouseout
: mouse has moved from a feature to an area without any features. Event has{ latLng: location, data: featureData }
as its data, in whichfeatureData
is the feature data the mouse was previously on.
Example:
map.gridLayer.on('click', function(e) {
if (e.data && e.data.url) {
window.open(e.data.url);
}
});
Returns this layer's TileJSON object which determines its tile source, zoom bounds and other metadata.
Example:
var layer = L.mapbox.gridLayer('mapbox.light')
// since layers load asynchronously through AJAX, use the
// `.on` function to listen for them to be loaded before
// calling `getTileJSON()`
.on('ready', function() {
// get TileJSON data from the loaded layer
var TileJSON = layer.getTileJSON();
});
Returns: the TileJSON object
Load data for a given latitude, longitude point on the map, and call the callback function with that data, if any.
Options | Value | Description |
---|---|---|
latlng | object | latlng a L.LatLng object |
callback | function | callback a function that is called with the grid data as an argument |
Returns: the L.mapbox.gridLayer object
Extends: L.FeatureGroup
L.mapbox.featureLayer
provides an easy way to integrate GeoJSON
from Mapbox and elsewhere into your map.
Options | Value | Description |
---|---|---|
id or url or geojson | string if id or url object if tilejson | Must be either
|
options | object | If provided, it is the same options as provided to L.FeatureGroup , as well as:
|
Example:
var featureLayer = L.mapbox.featureLayer(geojson)
.addTo(map);
Returns a L.mapbox.featureLayer
object.
Class: L.mapbox.FeatureLayer
Load GeoJSON data for this layer from the URL given by url
.
Options | Value | Description |
---|---|---|
url | string | A tileset ID |
Example:
var featureLayer = L.mapbox.featureLayer()
.addTo(map);
featureLayer.loadURL('my_local_markers.geojson');
Returns: the layer object
Load marker GeoJSON data from a map with the given id
on Mapbox.
Options | Value | Description |
---|---|---|
url (required) | string | A tileset ID |
Example:
var featureLayer = L.mapbox.featureLayer()
.addTo(map);
// loads markers from the map `mapbox.dark` on Mapbox,
// if that map has markers
featureLayer.loadID('mapbox.dark');
Returns: the layer object
Sets the filter function for this data layer.
Options | Value | Description |
---|---|---|
filter (required) | function | a function that takes GeoJSON features and returns true to show and false to hide features. |
Example:
var featureLayer = L.mapbox.featureLayer(geojson)
// hide all markers
.setFilter(function() { return false; })
.addTo(map);
See a live example of .setFilter
Returns the featureLayer object.
Gets the filter function for this data layer.
Example:
var featureLayer = L.mapbox.featureLayer(geojson)
// hide all markers
.setFilter(function() { return false; })
.addTo(map);
// get the filter function
var fn = featureLayer.getFilter()
Returns the filter function.
Set the contents of a markers layer: run 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.
Options | Value | Description |
---|---|---|
geojson (required) | object | features , an array of GeoJSON feature objects, or omitted to get the current value. |
Example:
var featureLayer = L.mapbox.featureLayer(geojson)
.addTo(map);
// a simple GeoJSON featureset with a single point
// with no properties
featureLayer.setGeoJSON({
type: "FeatureCollection",
features: [{
type: "Feature",
geometry: {
type: "Point",
coordinates: [102.0, 0.5]
},
properties: { }
}]
});
Returns the featureLayer object
Get the contents of this layer as GeoJSON data.
Returns the GeoJSON represented by this layer
Extends: L.tileLayer
L.mapbox.styleLayer
renders Mapbox Studio styles as raster tiles using the Mapbox Static Tiles API tiles endpoint.
Options | Value | Description |
---|---|---|
url | string | Must be a string like mapbox://styles/mapbox/cin286r4x006safncofpcb71v |
options | object | If provided, it is the same options as provided to L.tileLayer , as well as:
|
Example:
var styleLayer = L.mapbox.styleLayer(url)
.addTo(map);
Returns a L.mapbox.styleLayer
object.
A low-level interface to the Mapbox Geocoding API, useful for complex uses and reverse-geocoding.
Options | Value | Description |
---|---|---|
id or url | string | Value must be
|
options | Object | The second argument is optional. If provided, it may include:
|
Returns a L.mapbox.geocoder
object.
Queries the geocoder with a query string, and returns its result, if any. This performs forward geocoding.
Options | Value | Description |
---|---|---|
queryString (required) | string | a query, expressed as a string, like 'Arkansas' |
options | object | an object containing the query and options parameters like { query: 'Austin', proximity: L.latlng(lat, lng) } |
callback (required) | function | a callback |
Valid options are:
- proximity: a
L.LatLng
object or[latitude, longitude]
array that will bias the search results toward a geographical point - country: a string or array of strings of ISO country codes likes
us
orca
which will be included in the search. Ommitting this parameter (the default) includes all countries. - autocomplete: whether to include results that only contain the prefix
of the search terms rather than the full terms. If you have precise input,
set this to
false
. Otherwise, by default it istrue
.
The callback is called with arguments
-
An error, if any
-
The result. This is an object with the following members:
{ results: // raw results latlng: // a map-friendly latlng array bounds: // geojson-style bounds of the first result lbounds: // leaflet-style bounds of the first result }
Example: Live example of geocoder.query centering a map.
Returns: the geocoder object. The return value of this function is not useful - you must use a callback to get results.
Queries the geocoder with a location, and returns its result, if any. This performs reverse geocoding.
Options | Value | Description |
---|---|---|
location (required) | object | A query, expressed as an object:
|
callback (required) | function | The callback is called with arguments
|
Returns: the geocoder object. The return value of this function is not useful - you must use a callback to get results.
Extends: L.Control
A map control that shows legends added to maps in Mapbox. Legends are auto-detected from active layers.
Options | Value | Description |
---|---|---|
options optional | object | An options object. Beyond the default options for map controls, this object has one special parameter: sanitizer : A function that accepts a string, and returns a sanitized result for HTML display. The default will remove dangerous script content, and is recommended. |
Example:
var map = L.mapbox.map('map').setView([38, -77], 5);
map.addControl(L.mapbox.legendControl());
Returns: a L.mapbox.legendControl
object.
Class: L.mapbox.LegendControl
Adds a legend to the legendControl.
Options | Value | Description |
---|---|---|
legend required | string | A string which may contain HTML. It will be sanitized by the legendControl's sanitizer option. |
Removes a legend from the legendControl.
Options | Value | Description |
---|---|---|
legend required | string | legend data to remove. |
Extends: L.Control
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.
Options | Value | Description |
---|---|---|
layer | L.mapbox.gridLayer |
The first argument must be a layer created with L.mapbox.gridLayer() |
options | object | Valid options are:
|
Example:
var map = L.mapbox.map('map').setView([38, -77], 5);
var gridLayer = L.mapbox.gridLayer('mapbox.light');
map.addLayer(L.mapbox.tileLayer('mapbox.outdoors'));
map.addLayer(gridLayer);
map.addControl(L.mapbox.gridControl(gridLayer));
Returns: a L.mapbox.gridControl
object.
Class: L.mapbox.GridControl
If a tooltip is currently shown by the gridControl, hide and close it.
Returns: the L.mapbox.gridControl
object.
Change the Mustache template used to transform the UTFGrid data in the map's interactivity into HTML for display.
Options | Value | Description |
---|---|---|
template | string | A string of Mustache template code for popups. |
Returns: the L.mapbox.gridControl
object.
Adds geocoder functionality as well as a UI element to a map. This uses the Mapbox Geocoding API.
Options | Value | Description |
---|---|---|
id or url (required) | string | Either a
|
options | object | An options argument with the same options as the L.Control class, as well as:
|
The options
object can also include queryOptions
which are passed to the
geocoder.query
method: see that method for full documentation of those options.
Example:
var map = L.map('map')
.setView([37, -77], 5)
.addControl(L.mapbox.geocoderControl('mapbox.places'));
Returns a L.mapbox.geocoderControl
object.
Class: L.mapbox.GeocoderControl
Set the url used for geocoding.
Options | Value | Description |
---|---|---|
url | string | A geocoding url |
Returns: the geocoder control object
Set the tileset ID used for geocoding.
Options | Value | Description |
---|---|---|
id | string | A tileset ID to geocode from |
Returns: the geocoder control object
Set the TileJSON used for geocoding.
Options | Value | Description |
---|---|---|
tilejson | object | A TileJSON object |
Returns: the geocoder object
Bind a listener to an event emitted by the geocoder control. Supported additional events are
Event | Description |
---|---|
found | A successful search. The event's results property contains the raw results. |
notfound | A search request succeeded but didn't find any results. |
error | A network error. The event's error property contains the raw HTTP error. |
select | Fired when the user selects a location from a list of options returned from a geocoding request. The event's feature property contains the selected GeoJSON Feature. |
autoselect | Fired when the control automatically selects the first result of a query that returns only one result, and repositions the map accordingly. The event's feature property contains the selected GeoJSON feature. |
Adds a "Share" button to the map, which can be used to share the map to Twitter or Facebook, or generate HTML for a map embed.
Extends: L.Control
Options | Value | Description |
---|---|---|
id or url optional | string | Either a
|
options | object | Options for L.Control Also accepts the following options:
|
Example:
var map = L.map('map', 'mapbox.streets')
.setView([37, -77], 5)
.addControl(L.mapbox.shareControl());
Returns:
Returns a L.mapbox.shareControl
object.
A core icon generator used in L.mapbox.marker.style
Options | Value | Description |
---|---|---|
feature | object | A GeoJSON feature object |
Returns:
A L.Icon
object with custom settings for iconUrl
, iconSize
, iconAnchor
,
and popupAnchor
.
A working example of L.mapbox.marker.icon in use
An icon generator for use in conjunction with pointToLayer
to generate
markers from the Mapbox Markers API
and support the simplestyle-spec for
features.
Options | Value | Description |
---|---|---|
feature | object | A GeoJSON feature object |
latlng | object | The latitude, longitude position of the marker |
Examples:
L.geoJson(geoJson, {
pointToLayer: L.mapbox.marker.style,
});
Returns:
A L.Marker
object with the latitude, longitude position and a styled marker
The other sections of the simplestyle-spec are implemented
by L.mapbox.simplestyle.style
Given a GeoJSON Feature with optional simplestyle-spec properties, return an options object formatted to be used as Leaflet Path options.
Options | Value | Description |
---|---|---|
feature | object | A GeoJSON feature object |
Examples:
L.geoJson(geoJson, {
pointToLayer: L.mapbox.simplestyle.style,
});
A working example of L.mapbox.simplestyle in use
Returns:
An object formatted to be used as Leaflet Path options.
A HTML sanitization function, with the same effect as the default value of the sanitizer
option of L.mapbox.featureLayer
, L.mapbox.gridControl
, and L.mapbox.legendControl
.
Options | Value | Description |
---|---|---|
text | string | String of content you wish to sanitize. |
A mustache template rendering function, as used by the templating feature provided by L.mapbox.gridControl
.
Options | Value | Description |
---|---|---|
template | string | The template string |
data | object | Data you wish to pass into the template string |
Example:
var output = L.mapbox.template('Name: {% raw %}{{name}}{% endraw %}', {name: 'John'});
// output is "Name: John"
The API access token to be used by Mapbox.js. You must set this value as described in API access tokens.
By default, this is true
. Mapbox.js always requires HTTPS resources,
regardless of the host page's scheme.
Setting FORCE_HTTPS
to false
makes Mapbox.js auto-detect whether the page your map
is embedded in is using HTTPS or SSL, and matches: if you use HTTPS on your site,
it uses HTTPS resources.
Example:
L.mapbox.config.FORCE_HTTPS = false;
A base URL from which Mapbox.js will load TileJSON and other resources. By default, this points to the Mapbox Web Services.
The same as L.mapbox.config.HTTP_URL
, but used when SSL mode is detected or
FORCE_HTTPS
is set to true
.
Mapbox.js uses the Mapbox web services API, which requires an API access token. You must supply an access token to Mapbox.js:
L.mapbox.accessToken = '<your access token>';
To obtain an access token, sign in to Mapbox and visit the Account Apps page. For Mapbox.js, a "Public" token (starting with "pk") is required.
You may create multiple tokens and use different ones for different applications. If
necessary, you can use different tokens on the same page by using the accessToken
option when creating Mapbox.js objects. For example:
var map = L.mapbox.map('map', 'mapbox.outdoors', {
accessToken: '<your access token>'
});
For additional help, see "How do I create an API access token?".
In a few cases, you may need to make changes to code written for Mapbox.js 1.x versions in order to work with Mapbox.js 2.x.
-
Mapbox.js 2.x uses version 4 of the Mapbox web services API, which requires API access tokens. You must supply an access token to Mapbox.js; see API access tokens for details.
-
The
markerLayer
alias has been removed fromL.mapbox.map
. UsefeatureLayer
instead. For example, replace
map.markerLayer.setFilter(function(f) { ... });
with
map.featureLayer.setFilter(function(f) { ... });
L.mapbox.geocoder
andL.mapbox.geocoderControl
no longer accept arbitrary tileset IDs. Instead you must provide a predefined geocoder index ID (or the ID of a custom geocoder index). For instance, replace
L.mapbox.geocoderControl('mapbox.outdoors').addTo(map);
with
L.mapbox.geocoderControl('mapbox.places').addTo(map);
See the geocoding API documentation for a complete list of predefined geocoding indexes.
-
The format for
L.mapbox.geocoder
andL.mapbox.geocoderControl
results have changed. Results are now provided in GeoJSON format. If your code usesL.mapbox.geocoder
or thefound
,select
, orautoselect
events fromL.mapbox.geocoderControl
, it may need to be updated to expect the format documented in those classes. -
L.mapbox.config.HTTP_URLS
andL.mapbox.config.HTTPS_URLS
have been replaced withL.mapbox.config.HTTP_URL
andL.mapbox.config.HTTPS_URL
, which expect to be assigned a single URL rather than an array of URLs. For example, replace
L.mapbox.config.HTTP_URLS = ["http://example.com/"];
with
L.mapbox.config.HTTP_URL = "http://example.com/";
-
L.mapbox.tileLayer
no longer supportsdetectRetina
,retinaVersion
, orautoscale
options. Instead, retina tiles are always automatically used when available. -
L.mapbox.geocoder
no longer hassetURL
,setID
, andsetTileJSON
methods. Instead of resetting the URL or ID, construct a new instance with the desired URL or ID. Instead of setting TileJSON, construct an instance from the geocoding URL in the TileJSON.
Mapbox.js is optimized for mobile devices and small screens by default. There are, however, best practices to make sure your map always looks its best.
Modern mobile browsers now support scaling of webpages by leveraging the meta
tag viewport
. This enlarges the window making your map look better on a
mobile device. Simply include this in the head of your document:
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />
If you're planning on having a page that has large amounts of scrolling,
try to avoid a large map height. Having a 'tall' map can cause the user
to get stuck on the map while scrolling. Another way around this is to disable
dragging
for mobile devices: map.dragging.disable();
Mapbox.js implements a simple, light style on all interaction elements. A dark theme
is available by applying class="dark"
to the map div.
Example:
<div id="map" class="dark"></div>
By default, Mapbox.js includes a bundled version of Leaflet that Mapbox has ensured is compatible. A standalone version of Mapbox.js is also available which you can use if you would like to supply your own version of Leaflet. When using this technique, you will use the newest version of Mapbox.css.
<script src='{{site.tileApi}}/mapbox.js/{{site.mapboxjs}}/mapbox.standalone.js'></script>
<link href='{{site.tileApi}}/mapbox.js/{{site.mapboxjs}}/mapbox.css' rel='stylesheet' />
<script src='your version of Leaflet.js'></script>