MapboxGl Marker + Popup Close

by kmandov

HTML

<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.28.0/mapbox-gl.css">
<nav id="menu">
  <a href="#" id="open-popup">Open Popup</a>
  <a href="#" id="close-popup">Close Popup</a>  
</nav>
<div id="map">

</div>

CSS

#map { position:absolute; top:0; bottom:0; width:100%; }
#marker {
    background-image: url('https://www.mapbox.com/mapbox-gl-js/assets/washington-monument.jpg');
    background-size: cover;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    cursor: pointer;
}

.mapboxgl-popup {
    max-width: 200px;
}

   #menu {
        background: #fff;
        position: absolute;
        z-index: 1;
        top: 10px;
        right: 10px;
        width: 120px;
        border: 1px solid rgba(0,0,0,0.2);
        font-family: 'Open Sans', sans-serif;
    }

    #menu a {
        font-size: 13px;
        color: #666;      
        text-align: center;
        display: block;
        margin: 0;
        padding: 10px;
        text-decoration: none;    
        border-bottom: 1px solid rgba(0,0,0,0.25);        
    }

    #menu a:last-child {
        border: none;
    }

    #menu a:hover {
        background-color: #f3f3f3;
        color: #333;
    }

JavaScript

mapboxgl.accessToken = 'pk.eyJ1IjoibW9ycGhvY29kZSIsImEiOiJVMnRPS0drIn0.QrB-bpBR5Tgnxa6nc9TqmQ';

var monument = [-77.0353, 38.8895];
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    center: monument,
    zoom: 15
});

// create the popup
var popup = new mapboxgl.Popup({offset:[0, -30]})
    .setText('Construction on the Washington Monument began in 1848.');

// create DOM element for the marker
var el = document.createElement('div');
el.id = 'marker';

// create the marker
new mapboxgl.Marker(el, {offset:[-25, -25]})
    .setLngLat(monument)
    .setPopup(popup) // sets a popup on this marker
    .addTo(map);
    
document.getElementById('open-popup').onclick = function(e) {
	popup.addTo(map);
}

document.getElementById('close-popup').onclick = function(e) {
	popup.remove();
}