Andre
Andre

Reputation: 59

Custom slider zoom bar on mapbox gl js?

I'm trying to implement a zoom bar in mapbox gl js but the only thing I found is this code from their documentation which adds an +, - and a reset. Is there anyway I can add a slider zoom level bar ? (A bar like this https://www.w3schools.com/howto/howto_js_rangeslider.asp )

var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'bottom-left');

Upvotes: 0

Views: 1560

Answers (1)

jscastro
jscastro

Reputation: 3780

Yes, you can, it requires to create a custom control and add manually the event to update the map zoom... but it's only a few lines of code. I didn't work too much in the css styling.

How to create a custom zoom control here's a fiddle I have created with an example How to create a custom zoom control

And here's the relevant scripting code

<script>

    mapboxgl.accessToken = 'PUT HERE YOUR MAPBOX TOKEN';

    var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v11', // stylesheet location
        zoom: 3, // starting zoom
        center: [-95, 40], // starting position [lng, lat]
    });
    map.on('load', function () {

        let zoomControl = new CustomZoomControl();
        map.addControl(zoomControl, 'top-right');

        map.on('zoom', function () {
            zoomControl.update();
        });
    });

    class CustomZoomControl {

        onAdd(map) {
            this.map = map;

            this.container = document.createElement('div');
            this.container.className = " mapboxgl-ctrl mapboxgl-ctrl-group";

            this.input = document.createElement('input');
            this.input.type = "range"
            this.input.min = 1;
            this.input.max = 220;
            this.createAttribute(this.input , "value", map.getZoom()*10)
            this.input.className = "slider";
            this.input.id = "myRange";

            this.container.appendChild(this.input);

            // Update the current slider value (each time you drag the slider handle)
            this.input.oninput = function () {
                map.setZoom(this.value/10);
            }

            return this.container;
        }
        onRemove() {
            this.container.parentNode.removeChild(this.container);
            this.map = undefined;
        }

        createAttribute(obj, attrName, attrValue) {
            var att = document.createAttribute(attrName);
            att.value = attrValue;
            obj.setAttributeNode(att);
        }

        update() {
            let zoom = map.getZoom() * 10;
            if (this.input.value != zoom) this.input.value = zoom;
        }

    }

</script>

Upvotes: 1

Related Questions