[BNM] Can this convoluted JavaScript function be simplified?

Alex alex at fatdrop.co.uk
Sat Nov 8 15:52:23 GMT 2008


So you just want to confine the Lat values to values between -90 and 90 
and the Long between -180 and 180?



Premasagar Rose wrote:
> A little challenge for the weekend, perhaps?
>
> I've written a JavaScript function that gives me the results that I 
> need, but in quite a convoluted way. I've spent all my brain cells now 
> and can't think how to further simplify it. It'll probably involve more 
> use of modulus (%) or something.
>
> The function takes two numbers, which represent latitude and longitude 
> coordinates. The idea is that it will "normalise" any invalid 
> coordinates (e.g. further north than the north pole, or further west 
> than Alaska), so that they become valid again. It's part of geo plugin 
> for jQuery that I'm working on.
>
> Latitude runs from -90 at the south pole, to 0 at the equator, to 90 at 
> the north pole.
> Longitude runs from -180 west of Alaska, to 0 in the UK, to 180 east of 
> Fiji.
> For consistency, I have -180 longitude always represented as 180 (the 
> two coordinates are actually the same).
>
> The results of a simplified version should be absolutely identical. Any 
> suggestions on improving it?:
>
> ===
>
> function normalizeLatLng(lat, lng){
>     lat = lat % 360;
>     if (lat > 90 && lat <= 180){
>         lat = 180 - lat;
>         lng = lng - 180;
>     }
>     else if (lat > 180 && lat <= 270){
>         lat = 180 - lat;
>         lng = lng - 180;
>     }
>     else if (lat > 270 && lat <= 360){
>         lat = lat - 360;
>     }
>     else if (lat < -90 && lat >= -180){
>         lat = 0 - (lat + 180);
>         lng = lng - 180;
>     }
>     else if (lat < -180 && lat >= -270){
>         lat = 180 - lat;
>         lng = lng - 180;
>     }
>     else if (lat < -270 && lat >= -360){
>         lat = lat + 360;
>     }
>  
>     if (lng <= -180 || lng > 180){
>         lng = (lng % 180) - (lng > 0 ? 180 : -180);
>         if (lng === -180){
>             lng = 180;
>         }
>     }
>     return [lat,lng];
> }
>
> ===
>
>     I look forward to any suggestions.
>
>     Cheers,
>     Premasagar
>
>   

-- 
http://www.fatdrop.co.uk - digital music services
http://blog.fatdrop.co.uk - music industry blog

FATDROP LTD | Registered in England and Wales | Company No. 6199983



More information about the BNMlist mailing list. Powered by Wessex Networks