Viewing an older version of mapbox.js. Check out v1.4.0 for the latest.

Listing Markers In View

Filtering markers by the map extent


<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Listing Markers In View</title>
  <script src='http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.js'></script>
  <link href='http://api.tiles.mapbox.com/mapbox.js/v0.6.7/mapbox.css' rel='stylesheet' />
  <style>
    body { margin:0; padding:0; }
    #map { position:absolute; top:0; bottom:0; width:100%; }
  </style>
</head>
<body>
<style>
#onscreen {
    position:absolute;
    top:10px;
    left:10px;
    width:300px;
    height: 100px;
    background:#fff;
    z-index:100;
}
</style>
<div id='map'></div>
<pre id='onscreen'></pre>
<script>
var map = mapbox.map('map');
map.addLayer(mapbox.layer().id('examples.map-20v6611k'));

// Create an empty markers layer
var markerLayer = mapbox.markers.layer();

// Add interaction to this marker layer. This
// binds tooltips to each marker that has title
// and description defined.
mapbox.markers.interaction(markerLayer);
map.addLayer(markerLayer);

map.zoom(5).center({ lat: 37, lon: -77 });

for (var x = -120; x < 120; x += 20) {
    for (var y = -80; y < 80; y += 10) {
        markerLayer.add_feature({
            geometry: {
                coordinates: [x, y]
            },
            properties: {
                'marker-color': '#000',
                'marker-symbol': 'star-stroked',
                title: [x, y].join(',')
            }
        });
    }
}

// Attribute map
map.ui.attribution.add()
    .content('<a href="http://mapbox.com/about/maps">Terms &amp; Feedback</a>');

var onscreen = document.getElementById('onscreen');
map.addCallback('drawn', function() {
    // .markers() gives a list of markers, along with their elements attached.
    var markers = markerLayer.markers(),
        // construct an empty list to fill with onscreen markers
        inextent = [],
        // get the map extent - the top-left and bottom-right locations
        extent = map.extent()

    // for each marker, consider whether it is currently visible by comparing
    // with the current map extent
    for (var i = 0; i < markers.length; i++) {
        if (extent.containsLocation(markers[i].location)) {
            inextent.push(markers[i].data.properties.title);
        }
    }

    // display a list of markers.
    onscreen.innerHTML = inextent.join('\n');
});
</script>
The code and documentation to mapbox.js is hosted on GitHub where you can contribute changes and improvements.