Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert latitude, longitude and zoomLevel to latitudeDelta and longitudeDelta

I have a zoom level zoom=Z and a position latitude=x, longitude=y, but I need to set the region with latitude, longitude, latitudeDelta and longitudeDelta.

I have found the image

enter image description here

to explain how latitudeDelta and longitudeDelta works, as well as the formula

zoom = Math.round(Math.log(360 / region.longitudeDelta) / Math.LN2

But how can I convert the zoom level zoom=Z to latitudeDelta and longitudeDelta?

I would guess that I only need to set either latitudeDelta or longitudeDelta and then calculate the other value from the screen size?

like image 290
Jamgreen Avatar asked Oct 21 '17 07:10

Jamgreen


1 Answers

So having your formula for the zoom dependent on the longitudeDelta we can express the longitudeDelta with some basic math rules:

enter image description here

This way we convert the zoom to longitudeDelta. To find the latitudeDelta there are different ways. I prefer to find the coefficient between the longitudeDelta and the latitudeDelta, which will always be the same no matter the zoom level. Here is the sample code I wrote. I omitted the rounding for the zoom level to integer to show that the calculation are correct.

// Initial values
var latitudeDelta = 0.004757;
var longitudeDelta = 0.006866; 

var coef = latitudeDelta / longitudeDelta; // always the same no matter your zoom

// Find zoom level
var zoomLvlCalculated = calcZoom(longitudeDelta);
console.log(zoomLvlCalculated); // 15.678167523696594

// Find longitudeDelta based on the found zoom  
var longitudeDeltaCalculated = calcLongitudeDelta(zoomLvlCalculated);
console.log(calcLongitudeDelta(zoomLvlCalculated));// 0.006865999999999988 which is the same like the initial longitudeDelta, if we omit the floating point calc difference

// Find the latitudeDelta with the coefficient
var latitudeDeltaCalculated = longitudeDeltaCalculated * coef;
console.log(latitudeDeltaCalculated); //0.004756999999999992 which is the same like the initial latitudeDelta, if we omit the floating point calc difference

function calcZoom(longitudeDelta) {
    // Omit rounding intentionally for the example
    return Math.log(360 / longitudeDelta) / Math.LN2;
}

function calcLongitudeDelta(zoom) {
    var power = Math.log2(360) - zoom;
    return Math.pow(2, power);
}

P.S. Since Internet Explorer does not have support for log with base 2 you can use this formula to calculate with different base (e):

enter image description here

like image 124
antanta Avatar answered Nov 01 '22 05:11

antanta