oysega
Last Updated: May 19, 2018
·
177
· Wahlbarg

MapBox WEBGL fitBounds quick fix

Hello,

In MapBox , the fitBounds function will work only if we pass the SW first coords and then the NE coords, otherwise, the fnction will throw a message in the console :
"Map cannot fit within canvas with the given bounds, padding, and/or offset".
This message will show when try to pass the NE befor the SW in the bounding Array.
And it will show also if you have two points, one in the NW and the other in the SE.

This function will handel it for your, no matter the order of the your points or the position, it will always fit the view in to the given Coords points !

See it live : https://jsfiddle.net/wahlbarg/unqm9022/

The function :

function FitBounds(ArrayA,ArrayB)
{
var Box;

            if(ArrayA[0] > ArrayB[0] && ArrayA[1] > ArrayB[1])
            {
                Box = [ArrayB,ArrayA];
            }
            else if(ArrayB[0] > ArrayA[0] && ArrayB[1] > ArrayA[1])
            {
                Box = [ArrayA,ArrayB];
            }

        else if(ArrayA[0] > ArrayB[0] && ArrayA[1] < ArrayB[1])
        {
                var MirroPointA = [ArrayA[0],ArrayB[1]],
                        MirroPointB = [ArrayB[0],ArrayA[1]];
                                Box = [MirroPointB,MirroPointA];
        }

        else if(ArrayA[0] < ArrayB[0] && ArrayA[1] > ArrayB[1])
        {
                var MirroPointA = [ArrayB[0],ArrayA[1]],
                        MirroPointB = [ArrayA[0],ArrayB[1]];
                                Box = [MirroPointB,MirroPointA];
        }

Map.fitBounds(Box,{
                                      padding : {
                                        top: 80,
                                        right:80,
                                        bottom:80,
                                        left:80
                                                        }
                                    } );

}

Say Thanks
Respond

3 Responses
Add your response

29729
12 1510738735134

For those writing JavaScript with r.js compiler, pragmas can be very useful for this kind of thing.

Ready to play amazing games for free Run 3: https://run3coolmath.io/

2 months ago ·
29783

Thanks for your sharing! The information your share is very useful to me and many people are looking for them just like me!
http://run3-game.com >Run 3

about 2 months ago ·
29916

The article is interesting and useful. I tried it and found it really useful. Thank you very much. https://www.hotmailissue.com

7 days ago ·