Javascript DD2DMS

2007-11-21

I'm working on a Google Maps oriented project and I've dug up some information about how the coordinate system works. I can recognize that 52º5'52"N, 5º13'11"E are coordinates, but I never bothered to look up what it means.

And now I do, to some degree. I found a fairly clear explanation here while searching for a simple javascript to convert the coordinates of one system to another.

There are several systems to indicate a location on earth (also called a geolocation). The most familiar, I think, is the degree minute second system or DMS, 52º5'52"N, 5º13'11"E. Another system is the decimal degree system or DD, 52.09765117899479, 5.219843611121178. The DD system is more accurate (but by far the most accurate) than DMS but in DMS you can compensate by not rounding down the seconds. Other systems for geolocations don't really matter right now (although I did like MGRS).

After encountering a heap of crappy or bloated scripts I decided to reinvent the wheel. This is what it became :)

Code: (JS)
/**
* returns a DMS notation string of the latlng coordinates
* qfox.nl 2007
*/
function dd2dms(floatLat, floatLon) {
var d2s = function(floatCoord) {
var intDeg = Math.floor(floatCoord);
var intMin = Math.floor((floatCoord - intDeg) * 60);
var intSec = Math.round(((floatCoord - intDeg) - (intMin / 60)) * 60*60);
return intDeg+"º"+intMin+"'"+intSec+'"';
}
var strDmsLat = d2s(Math.abs(floatLat))+(floatLat>0?"N":"S" );
var strDmsLon = d2s(Math.abs(floatLon))+(floatLon>0?"E":"W" );
return strDmsLat+", "+strDmsLon;
}

After this, the reverse should be trivial.

Hope it helps you.