Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 638
user3683414 Avatar asked May 28 '14 11:05

user3683414


1 Answers

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...

like image 69
sfletche Avatar answered Oct 06 '22 01:10

sfletche