Skip to content

Instantly share code, notes, and snippets.

@johnlonganecker
Last active March 9, 2024 14:00
Show Gist options
  • Save johnlonganecker/6afc36514a9661963734 to your computer and use it in GitHub Desktop.
Save johnlonganecker/6afc36514a9661963734 to your computer and use it in GitHub Desktop.
Leaflet minZoom based on screen resolution. Fit up to one globe.
// Get the largest screen dimension
// reason for doing this is a phone may start in portrait then move to landscape
var maxScreenDimension = window.innerHeight > window.innerWidth ? window.innerHeight : window.innerWidth;
// assuming tiles are 256 x 256
var tileSize = 256;
// How many tiles needed to for the largest screen dimension
// I take the floor because I don't want to see more then 1 world
// Use Math.ceil if you don't mind seeing the world repeat
var maxTiles = Math.floor(maxScreenDimension / tileSize);
/* MATH MAGIC !!!!!
number of tiles needed for one side = 2 ^ zoomlevel
or
maxTiles = 2 ^ zoomlevel
Time to show my steps! assuming log base 2 for all steps
log(2 ^ zoomlevel) = log(maxTiles)
properties of logs
zoomlevel * log(2) = log(maxTiles)
log base 2 of 2 is just 1
zoomlevel * 1 = log(maxTiles)
JS Math.log is ln (natural log) not base 2
So we need to use another log property
Math.log(maxTiles) / Math.log(2) = Log base 2 of maxTiles
*/
// I am taking the ceiling so I don't see more then 1 world
// Use Math.floor if you don't mind seeing the world repeat
minZoom = Math.ceil(Math.log(maxTiles) / Math.log(2));
// only let minZoom be 2 or higher
minZoom = minZoom < 2 ? 2 : minZoom;
// plug this into L.map() options
L.map('map', {
// ...
minZoom: minZoom
// ...
});
@Joepublicuntited
Copy link

awesome! was looking all over for something like this! :) (y)

@mojimi
Copy link

mojimi commented Feb 1, 2023

What variable should I change if I wanted to fit less than one globe?

@mojimi
Copy link

mojimi commented Feb 1, 2023

I'm also assuming that we can precalculate this given a list of breakpoints right? Lets say I only care about supporting 5 difference screen sizes

@johnlonganecker
Copy link
Author

johnlonganecker commented Feb 1, 2023

Only place that takes in screen size is line 3:

var maxScreenDimension = window.innerHeight > window.innerWidth ? window.innerHeight : window.innerWidth;

Screen size is grabbed dynamically from the device. Add some if statements if you want to only grab for certain screen sizes!

See:
https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth
https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment