Leaflet responsive design - creating different zoom levels for different screen sizes using JavaScript

javascript, leaflet, mapbox, responsive-design, zooming

Solution

You can listen for screen resize events with javascript like this

// listen for screen resize events
window.addEventListener('resize', function(event){
    // get the width of the screen after the resize event
    var width = document.documentElement.clientWidth;
    // tablets are between 768 and 922 pixels wide
    // phones are less than 768 pixels wide
    if (width < 768) {
        // set the zoom level to 10
        map.setZoom(10);
    }  else {
        // set the zoom level to 8
        map.setZoom(8);
    }
});

Alternatively, rather than listen for screen resizes, you may just want to get the screen width once, at the moment you create the map...

Problem

I am new to Leaflet - though started with a free MapBox map. I have created a Website with media queries. I added a MapBox map to my index file with the following code: ``` <section id="map_section"> <div id='map'></div> <script> var map = L.mapbox.map('map', 'pandora.hn8og4ae', { scrollWheelZoom: false, minZoom: 5, maxZoom: 18 }).setView([45, -67.874], 8); </script> </section> ``` On smaller screen sizes (mobile devices) I would like to have the map initiate at a different zoom level because I don't have enough screen size to show all of my markers at once. How would you do this in css? A helpful person at MapBox suggested the following: You would need to do this programatically in JavaScript listening for a window resize event and setting map.setZoom(NUMBER) when a user's screen hits a particular size. Would anyone mind walking me through how to do this? I have taken baby steps into JavaScript and understand just enough to be dangerous. :) My organization is checking out Leaflet to produce a much larger project and this is an essential question for us. So even though I am using a MapBox example, we are moving directly to Leaflet.

Original source