Legacy
Mapbox.js is no longer in active development. To learn more about our newer mapping tools see Mapbox GL JS.
Open popup programmatically
Open a markers popup from a button.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Open popup programmatically</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.ui-control {
position:absolute;
top:10px;
right:10px;
z-index:1000;
}
</style>
<div id='map'></div>
<button id='open-popup' class='ui-control'>open popup</button>
<script>
L.mapbox.accessToken = '<your access token here>';
var map = L.mapbox.map('map')
.setView([37.77396, -122.4366], 12)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
var myFeatureLayer = L.mapbox.featureLayer('/mapbox.js/assets/data/sf_locations.geojson')
.addTo(map);
// Wait until the markers are loaded, so we know that `map.featureLayer.eachLayer`
// will actually go over each marker.
myFeatureLayer.on('ready', function(e) {
document.getElementById('open-popup').onclick = clickButton;
});
function clickButton() {
myFeatureLayer.eachLayer(function(marker) {
// You can replace this test for anything else, to choose the right
// marker on which to open a popup. by default, popups are exclusive
// so opening a new one will close all of the others.
if (marker.feature.properties.title === 'La Taqueria') {
marker.openPopup();
}
});
}
</script>
Get a free Mapbox account 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.