EN
JavaScript - convert longitude and latitude from degrees, minutes, and seconds (DMS) to decimal degrees (DD)
3
points
TODO: it is required to add seconds support to
parseCordinate()
function to the article in the future.
In this article, we would like to show how in JavaScript convert longitude and latitude from degrees, minutes, and seconds (DMS) format to decimal degrees (DD) / floating point numbers.
Example calculations:
0°00′N/S 0°00′E/W ---> 0 0
0°00'N/S 0°00'E/W ---> 0 0
51°53′N 176°39′W ---> 51.88333 -176.65
51°53'N 176°39'W ---> 51.88333 -176.65
Practical example:
// ONLINE-RUNNER:browser;
const SPACE_EXPRESSION = /\s+/;
const LATITUDE_EXPRESSION = /^(\d{1,2})°(?:\s*(\d{1,2})[′'])?\s*(N|S|N\/S)$/; // 0- 90° 0-59′ N/S
const LONGITUDE_EXPRESSION = /^(\d{1,3})°(?:\s*(\d{1,2})[′'])?\s*(E|W|E\/W)$/; // 0-180° 0-59′ E/W
const matchText = (expression, text) => {
expression.lastIndex = 0;
return expression.exec(text);
};
const parseCordinate = (expression, limit, surfaces, text) => {
const match = matchText(expression, text);
if (match) {
const degrees = parseInt(match[1]); // 0-90° or 0-180°
if (degrees > limit) {
throw new Error('Incorrect degrees value (should be in range from 0 to ' + limit + ').');
}
const minutes = parseInt(match[2] || '0'); // 0-59′
if (minutes > 59) {
throw new Error('Incorrect minutes value (should be in range from 0 to 59).');
}
if (degrees === 0 && minutes === 0) {
return 0;
}
const surface = match[3]; // N/S or E/W
switch (surface) {
case surfaces[0]: return +(degrees + minutes / 60);
case surfaces[1]: return -(degrees + minutes / 60);
default:
throw new Error('Incorrect surface value (should be ' + surfaces[0] + ' or ' + surfaces[1] + ').');
}
}
throw new Error('Incorrect cordinate format.');
};
const parseLatitude = (latitude) => parseCordinate(LATITUDE_EXPRESSION, 90, 'NS', latitude);
const parseLongitude = (longitude) => parseCordinate(LONGITUDE_EXPRESSION, 180, 'EW', longitude);
const parsePosition = (position) => {
if (position) {
const parts = position.split(SPACE_EXPRESSION);
if (parts.length === 2) {
const latitude = parseLatitude(parts[0]);
const longitude = parseLongitude(parts[1]);
return {latitude, longitude};
}
}
return new Error('Incorrect position format.');
};
// Usage example:
// 51°53′N 176°39′W ---> 51.88333 -176.65
//
const latitude = parseLatitude('51°53′N'); // 51.88333
const longitude = parseLongitude('176°39′W'); // -176.65
const position = parsePosition('51°53′N 176°39′W'); // 51.88333 -176.65
console.log(latitude); // 51.88333
console.log(longitude); // -176.65
console.log(JSON.stringify(position)); // {"latitude":51.88333333333333,"longitude":-176.65}