Leaflet – Calculating Correct Longitude When It’s Over 180 Degrees

javascriptlatitude longitudeleaflet

I'm trying to develop a "formula" to correct the lat-lng values.

I'm using vue-leaflet but when you pan outside the "first" world you get big numbers. Over +180 or under -180.

For example: when I pan to America to the right (east direction), I get as lng 215.
In my mind, I would just correct it with 215-360=-145

The same is for when I pan to east russia to the left (west direction) and I get for example -222. Now I need to calculate -222+360=138

However, since the world is indefinite the user could pan to the 8th world and I had to adjust the values.

Is it possible to calculate the right longitude? (and another requirement is when the user is in the first world, 24 lng should still be 24 lng.

Best Answer

You need to repeatedly add (or subtract) 360 to your value until it lies in the range of -180 - 180. So usually a pair of loops like:

lon = -187;
while(lon < -180){
  lon +=360;
}
while (lon > 180){
  lon -= 360;
}