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.

up vote 13 down vote accepted

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;
}
  • signs wrong way round? Should be lon +=360 in first case. – JimT Nov 20 at 9:37
  • 2
    bleeugh, coding before coffee. Thanks – Ian Turton Nov 20 at 9:38
  • 4
    you can do it with only one loop while (Math.abs(lon) > 180) { lon -= Math.sign(lon) * 360 } I am not providing it as an answer though because your version actually matches the explanation, while my version is just an optimization that likely doesn't make any difference. I keep it as a comment only as a reminder that things can be done in multiple ways, some more optimized than others. – Andrei Nov 20 at 10:38
  • 2
    I don't think I would ever use that one as it uses 2 function calls per loop and only one of my loops would ever execute. Probably makes no difference in this example but that's my prejudice – Ian Turton Nov 20 at 10:42
  • 2
    You can't do lon %= 180? – Nic Hartley Nov 20 at 17:39

An answer that avoids conditionals and function calls:

longitude = (longitude % 360 + 540) % 360 - 180

I wrote a quick microbenchmark at https://jsperf.com/longitude-normalisation and the conditional code seems to be faster (in Chrome on my machine) for 'reasonable' ranges of input values. In general you probably shouldn't be worrying in advance about performance in small calculations like this, giving more weight to readability and consistency with the rest of your codebase.

Probably more important in this case is the question of whether your code could ever come across extreme input values (1e10, Infinity etc.). If so, the looping implementation could end up running really slowly or silently hanging your program. This might occur with calculations performed near the poles, e.g. trying to pan east or west by some distance (rather than angle) from a pole could easily result in an infinite longitude.

  • 1
    Interesting. Let's race a conditional jmp against a FP divide. Hmmm I wonder. – Joshua Nov 20 at 20:12
  • 1
    @Joshua You can't use a conditional jump. You have to use multiple conditional jumps, aka a loop. (Plus the loop contains floating point additional, which isn't free.) How many iterations the loop needs depends on the input. So you have to know something about the data to look at performance. If the vast majority are near the desired range and require few iterations, sure, the addition loop might be faster, but it isn't as obvious as your sarcasm suggests. – jpmc26 Nov 20 at 22:11
  • 1
    @jpmc26: In this case, expecting to go around the loop more than once is silly. – Joshua Nov 20 at 22:13
  • 1
    There was no sarcasm. I actually don't know which way it would fall. – Joshua Nov 20 at 22:13
  • 1
    @Joshua yep, I wasn't sure either :). I added more to the answer on performance (and a potential failure case of the loop code) – Joe Lee-Moyet Nov 21 at 0:50

One-liner:

normalized = remainder(longitude, 360);

Explanation: You want to know what remains after you disregard full rotations (360°).

This process is called normalizing.

Example (cpp.sh)

  • 1
    Wouldn't this result in a [0, 360) value, not [-180, 180] as Shadrix requested? – The Guy with The Hat Nov 20 at 16:05
  • @TheGuywithTheHat Check this example: cpp.sh/7uy2v – Peter Paff Nov 20 at 16:26
  • Ah, didn't know this was C++. In Shadrix's context of JavaScript, I interpreted remainder as modulus. Modulus in JS would result in [0, 360). – The Guy with The Hat Nov 20 at 16:37
  • 1
    I don't think that would work. You would need to subtract 360 iff result > 180. Another problem I just realized with JavaScript is that modulo is symmetrical across 0, e.g. -1 % 3 is -1, not 2 as would be necessary for it to work here. remainder is a great C++ solution, but unfortunately there's just no function/operator in JS that's similar enough to be useful. – The Guy with The Hat Nov 20 at 17:31

Another option: longitude = atan2(cos(long), sin(long))

  • 1
    This doesn't seem like a good idea. It's very hard to understand, computationally expensive and potentially subject to rounding errors. – David Richerby Nov 20 at 19:07

If the programming language you're using supports the % (mod) operator on floating point numbers (like Python and Ruby), I'd recommend using that. Otherwise, some other languages (like C and C++) allow you to use fmod().

(Whichever mod operator you use, make sure ahead of time that it will do mod operations on floating-point numbers, and that it'll always give you non-negative answers. Otherwise you'll get a nasty surprise later when many of your lat/lon points are not correct.)

Use it like this:

# Put the longitude in the range of [0,360):
longitude %= 360

# Put the longitude in the range of [-180,180):
if longitude >= 180:
    longitude -= 360

If you'd prefer to do it all in one line:

# Put the longitude in the range of [-180,180):
longitude = (longitude + 180) % 360 - 180

These approaches have no loops, so they'll normalize longitude values without needing to repeatedly add or subtract, no matter how many times your observation has circled around the earth.

Edit:

Hmmm... I just noticed that Javascript doesn't seem to handle % with negative values like I thought it would.

In that case, try this one-liner:

longitude = (longitude + 36180) % 360 - 180

The 36180 we're adding is 36,000 + 180. The 36,000 is to move a negative value into the positive domain, and the 180 is to shift it over so that when it is modded by 360, it'll be in the range of [0,360). The - 180 part shifts it back to the range of [-180,180).

Here's another one-liner, one that doesn't rely on 36,000 being big enough:

longitude = (longitude % 360 + 360 + 180) % 360 - 180

The longitude % 360 + 360 part will ensure the value stays in the positive domain when it's later modded by 360. The + 180 part shifts it over so that when it later gets 180 subtracted from it (with - 180), it'll be in the desired range of [-180,180).

  • 1
    Note: C,C++ fmod(longitude, 360) --> (-360.0 ... +360.0) and ilongitude % 360 --> [-359 ... +359]. – chux Nov 21 at 6:01
  • @chux - I didn't know about that, so I just tested it, and it appears that you are correct. Thank you for pointing that out. – J-L Nov 21 at 16:47

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.