11const coordinatesRegex = / ^ ( \d { 2 } ) ( \d { 2 } ) ( [ N S ] ) \s + ( \d { 3 } ) ( \d { 2 } ) ( [ E W ] ) $ /
22export const decimalRegex = / ^ ( \d + \. \d + ) ( [ N S ] ) \s ( \d + \. \d + ) ( [ E W ] ) $ /
3+
4+ const MAX_LATITUDE = 90
5+ const MAX_LONGITUDE = 180
6+
7+ function toDecimal ( degrees , minutes , direction , maxDegrees , negativeDirection ) {
8+ if ( minutes >= 60 || degrees > maxDegrees ) {
9+ return undefined
10+ }
11+ const decimal = degrees + minutes / 60
12+ return `${ direction === negativeDirection ? "-" : "" } ${ decimal . toFixed ( 5 ) } `
13+ }
14+
315export function convertToDecimal ( input ) {
416 if ( ! input ) {
517 return ""
@@ -17,32 +29,19 @@ export function convertToDecimal(input) {
1729 }
1830 }
1931
20- // Extract latitude and longitude parts
2132 const latMatch = input . match ( coordinatesRegex )
22-
23- // Check if the input format is valid
24- if ( latMatch ) {
25- // Extract degrees, minutes, and direction
26- const latDegrees = parseInt ( latMatch [ 1 ] )
27- const latMinutes = latMatch [ 2 ]
28- const latDirection = latMatch [ 3 ]
29- const lonDegrees = parseInt ( latMatch [ 4 ] )
30- const lonMinutes = latMatch [ 5 ]
31- const lonDirection = latMatch [ 6 ]
32-
33- // Calculate decimal coordinates with proper sign for direction
34- const decimalLat = `${ latDirection === 'S' ? "-" : "" } ${ ( latDegrees + ( latMinutes / 60 ) ) . toFixed ( 5 ) } `
35- const decimalLon = `${ lonDirection === 'W' ? "-" : "" } ${ ( lonDegrees + ( lonMinutes / 60 ) ) . toFixed ( 5 ) } `
36-
37- // Return the result as an object
38- return {
39- lat : decimalLat ,
40- lon : decimalLon
41- } ;
42- } else {
33+ if ( ! latMatch ) {
4334 console . warn ( `Invalid coordinate format ${ input } ` )
4435 return undefined
4536 }
37+
38+ const lat = toDecimal ( parseInt ( latMatch [ 1 ] ) , parseInt ( latMatch [ 2 ] ) , latMatch [ 3 ] , MAX_LATITUDE , 'S' )
39+ const lon = toDecimal ( parseInt ( latMatch [ 4 ] ) , parseInt ( latMatch [ 5 ] ) , latMatch [ 6 ] , MAX_LONGITUDE , 'W' )
40+ if ( lat === undefined || lon === undefined ) {
41+ return undefined
42+ }
43+
44+ return { lat, lon}
4645}
4746
4847export function convertNmToUnlocodeText ( nm ) {
@@ -88,4 +87,4 @@ export function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
8887
8988function deg2rad ( deg ) {
9089 return deg * ( Math . PI / 180 )
91- }
90+ }
0 commit comments