Calculating correct longitude when it's over |180|?
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;
}
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.
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)