Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit map to show world always

Right now what I'm trying to do is zoom the map in and out based on screen size, so that you can always see basically every piece of land in the world. I'm not worried about the repeating world, but I ideally want to keep it centered basically on the west coast of Africa, like a typical map.

I have something that looks as follows:

function fitMap() {
    if ($) {
        var height = $(window).height();
        var width = $(window).width();
        //Put map into full screen
        $('#map').css({position: "absolute", top: "0", left: "0", right: "0", bottom:"0"});

        if ((height < 586 && width < 1095) || height < 325 || (width < 700 && height > 586)) {
            map.setZoom(1);
        }
        else if (width >= 1500 && height > 900) {
            map.setZoom(3);
        } 
        else {
            map.setZoom(2);
        }
    }
};

//Fit the map more appropriately to screen sizes.
window.onload = fitMap;
window.onresize = fitMap;

I find this to be really hacky and it works if I were to try and put this on a 1920x1080 all the way down to a small 1024x768 but I didn't see anything in Leaflet that would allow me to do this. One idea I had was to create an invisible feature group that basically creates a perimeter from dateline to dateline and use .getBounds() like this: Centering Leaflet map with getbounds and related issues

Does anyone have a better solution?

like image 361
Jacob Morrison Avatar asked Jul 24 '13 15:07

Jacob Morrison


Video Answer


1 Answers

Leaflet offers a fitWorld() method to do just this.

You would use this by calling map.fitWorld();, and here's a full example.

like image 141
Brett DeWoody Avatar answered Oct 16 '22 23:10

Brett DeWoody