Categories
JavaScript Answers

How to Convert Latitude and Longitude to Decimal Values with JavaScript?

Spread the love

Sometimes, we want to convert latitude and longitude to decimal values with JavaScript.

In this article, we’ll look at how to convert latitude and longitude to decimal values with JavaScript.

Convert Latitude and Longitude to Decimal Values with JavaScript

To convert latitude and longitude to decimal values with JavaScript, we can extract the numerical and directional parts of the latitude and longitude values into an array.

Then we can calculate the coordinate values from the extracted values.

For instance, we write:

const convertDMSToDD = (degrees, minutes, seconds, direction) => {
  let dd = +degrees + +minutes / 60 + +seconds / (60 * 60);
  if (direction === "S" || direction === "W") {
    dd = dd * -1;
  }
  return dd;
}

const parseDMS = (input) => {
  const parts = input.split(/[^\d\w]+/);
  const lat = convertDMSToDD(parts[0], parts[1], parts[2], parts[3]);
  const lng = convertDMSToDD(parts[4], parts[5], parts[6], parts[7]);
  return [lat, lng]
}

const coords = parseDMS(`36°57'9" N 110°4'21" W`)
console.log(coords)

to create the convertDMSToDD function that takes the degrees, minutes, seconds, and direction parameters.

Then we get the number part of the coordinates value with +degrees + +minutes / 60 + +seconds / (60 * 60) and assign the returned value to dd.

We convert number string to a number with the unary + operator.

If direction is 'S' or 'W', we multiply the dd value by -1.

And then we return dd.

Next, we create the parseDMS function with the input string.

We call split to split the string into numbers and the direction parts with /[^\d\w]+/.

Then we call convertDMSToDD with the extracted parts and return the values.

Therefore, from the console log, we see that coords is [36.9525, -110.07249999999999].

Conclusion

To convert latitude and longitude to decimal values with JavaScript, we can extract the numerical and directional parts of the latitude and longitude values into an array.

Then we can calculate the coordinate values from the extracted values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *