Fit map to markers

Automatically fit your data on your map with fitBounds with Mapbox.js, our open source JavaScript library.

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Fit map to markers</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css' rel='stylesheet' />
<style>
  body { margin:0; padding:0; }
  #map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
L.mapbox.accessToken = '<your access token here>';
var map = L.mapbox.map('map', 'mapbox.streets')
    .setView([38, -102.0], 9);

// As with any other AJAX request, this technique is subject to the Same Origin Policy:
// http://en.wikipedia.org/wiki/Same_origin_policy
// So the CSV file must be on the same domain as the Javascript, or the server
// delivering it should support CORS.
var featureLayer = L.mapbox.featureLayer()
    .loadURL('/mapbox.js/assets/data/eastcoast_cities.geojson')
    .addTo(map);

// Especially with dynamic data, it's useful to automatically fit all markers
// in the map bounds instead of guessing and checking center and zoom values

// Since this layer is loaded with the asynchronous method loadURL, that uses
// AJAX in the background, we wait for all of the markers to be loaded by
// waiting for the ready event. If you don't load your markers with an async
// method and instead set them with setGeoJSON or similar, you don't need
// to do this.
featureLayer.on('ready', function() {
    // featureLayer.getBounds() returns the corners of the furthest-out markers,
    // and map.fitBounds() makes sure that the map contains these.
    map.fitBounds(featureLayer.getBounds());
});
</script>
to create your own custom map and use it in this example.
Use this example by copying its source into your own HTML page and replacing the Map ID with one of your own from your projects. Having trouble with JavaScript? Try out Codecademy or contact our support team.
Copy example