Skip to content

Instantly share code, notes, and snippets.

@GastonZalba
Created September 1, 2020 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GastonZalba/23fd2e2c8f371c2dde3b7dff4460f802 to your computer and use it in GitHub Desktop.
Save GastonZalba/23fd2e2c8f371c2dde3b7dff4460f802 to your computer and use it in GitHub Desktop.
Convert decimal degree coordinate string formats to a clean array.
/**
* Latitude and longitude decimal values are bounded by ±90° and ±180° respectively.
* This will match only that bound, accepting common uses of commas, points, spaces,
* tabs and degree symbols, returning a clean, standardized latitude and longitude array.
* @returns [{number}, {number}] Latitude and longitude
*/
const parseDecimalLatLon = string => {
let isDecimal = /^([-+]?(?:[1-8]?\d(?:(?:.|,){1}\d+)?|90(?:\.0+)?))°?(?:,|;|\t| )+([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:(?:\.|\,){1}\d+)?))°?$/
let match = string.match(isDecimal);
if (!match) return false;
let lat = Number(match[1].replace(',', '.'));
let lon = Number(match[2].replace(',', '.'));
return [lat, lon];
}
/*
This will match:
-34.474963 -58.597759
-34.474963 -58.597759
-34.474963 -58.597759
-34.474963; -58.597759
-34.474963, -58.597759
-34,474963; -58,597759
-34.474963,-58.597759
+90.0000, -127.554334
-90.000, -180.0000
45, 180
-90, -180
+90, +180
45, 179.99999999
38.8897°, -77.0089°
This will NOT match:
-34.474963
45, 180.99999999
-90., -180.
+90.1, -100.111
-91, 123.456
*/
let result = parseDecimalLatLon('-34.474963,-58.597759')
result[0] // -34.474963
result[1] // -58.597759
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment