Making the Initial Zoom Level Responsive in Leaflet.js

Making the Initial Zoom Level Responsive in Leaflet.js

When designing websites and web applications, we consider how the page will display across various screen sizes. The same logic should apply to the initial zoom level of a web map.

I will be providing a short code snippet on how to set the initial zoom level of a Leaflet.js web map based upon the width of the screen. We will create a function that returns the zoom option for the L.map object. The function will perform a series of conditional tests upon the window.innerWidth property. It should be noted this property includes any rendered vertical scrollbar. Please refer to this article about how to obtain the viewport width excluding a scrollbar.

Function to set initial map zoom

function setInitialMapZoom() {

  var viewportWidth = window.innerWidth;

  var mapZoom;

  if (viewportWidth < [x]) {

   mapZoom = [a];

}  else if (viewportWidth >= [x] && viewportWidth < [y]) {

   mapZoom = [b];

}  else {

   mapZoom = [c];

}

return mapZoom;

}

 

In the above example, x and y are integer values representing the viewport width in pixels. a, b and c represent different zoom levels for the map. The output for this function (mapZoom) will an integer that corresponds to the zoom property of the map object.

The next step would be to tie this function to the code to create the map object.

Creating the map object

var map = L.map('map', {

  center: [lat, long],

  zoom: setInitialMapZoom()

});

In the above example, lat and long are floating point numbers that represent the geographic center of the map. An example would be 40.256 and -76.526. We set the zoom property to our function setInitialMapZoom() so that the the proper zoom level will be assigned based upon the viewport width.

As you have read, it is fairly straightforward to base the initial zoom level of a Leaflet web map on the viewport width of a screen.

Thank you, it helped me a lot

Like
Reply

very good. but not work for me.

Like
Reply

Thanks for the catch. I've actually moved my blogging to Wordpress at https://pnmcartodesign.wordpress.com/. I've found it to be a better writing experience, especially with code samples.

Like
Reply

Fantastic! Thank you for this. ps: you missed a ")" right after [y]

Like
Reply

To view or add a comment, sign in

Others also viewed

Explore content categories