3d Buildings

Mapbox GL 3d buildings

by Keir Clarke

HTML

<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.26.0/mapbox-gl.css">
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.26.0/mapbox-gl.js"></script>
<div id='map'></div>

CSS

body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }

JavaScript

mapboxgl.accessToken = 'pk.eyJ1IjoiZ21hcHNtYW5pYSIsImEiOiJOYnlnSFpvIn0.5f62d0cnrWCA1KioxzXtqg';
    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/light-v9',
        center: [-87.6298, 41.8781],
        zoom: 15,
        bearing: -12,
        pitch: 60,
        interactive: false
    });

    // pixels the map pans when the up or down arrow is clicked
    var deltaDistance = 100;

    // degrees the map rotates when the left or right arrow is clicked
    var deltaDegrees = 25;

    function easing(t) {
        return t * (2 - t);
    }

    map.on('load', function() {
        map.getCanvas().focus();

        map.getCanvas().addEventListener('keydown', function(e) {
            e.preventDefault();
            if (e.which === 38) { // up
                map.panBy([0, -deltaDistance], {
                    easing: easing
                });
            } else if (e.which === 40) { // down
				       setTimeout(function(){ map.setLight({color: "#fff", intensity: 1, position: [1.15, 135, 45]}); }, 200);
    			     setTimeout(function(){map.setLight({color: "#fff", intensity: 0.5, position: [1.15, 135, 45]}); }, 400);                
            } else if (e.which === 37) { // left
                map.easeTo({
                    bearing: map.getBearing() - deltaDegrees,
                    easing: easing
                });
            } else if (e.which === 39) { // right
                map.easeTo({
                    bearing: map.getBearing() + deltaDegrees,
                    easing: easing
                });
            }
        }, true);
    });
	
	map.on('load', function() {
    map.addLayer({
        'id': '3d-buildings',
        'source': 'composite',
        'source-layer': 'building',
        'filter': ['==', 'extrude', 'true'],
        'type': 'fill',
        'minzoom': 15,
        'paint': {
            'fill-color': '#aaa',
            'fill-extrude-height': {
                'type': 'identity',
      ...