How to validate latitude and longitude
The latitude must be a number between -90 and 90 and the longitude between -180 and 180.
Here are the functions to validate it in JavaScript.
- Latitude must be a number between -90 and 90
const isLatitude = num => isFinite(num) && Math.abs(num) <= 90;
- Longitude must a number between -180 and 180
const isLongitude = num => isFinite(num) && Math.abs(num) <= 180;
Using follow latitude and longitude regular expressions, we can validate.
With escape characters in Objective-C:
Latitude RegEx:
@"^(\\+|-)?((\\d((\\.)|\\.\\d{1,6})?)|(0*?[0-8]\\d((\\.)|\\.\\d{1,6})?)|(0*?90((\\.)|\\.0{1,6})?))$"
Longitude RegEx:
@"^(\\+|-)?((\\d((\\.)|\\.\\d{1,6})?)|(0*?\\d\\d((\\.)|\\.\\d{1,6})?)|(0*?1[0-7]\\d((\\.)|\\.\\d{1,6})?)|(0*?180((\\.)|\\.0{1,6})?))$"
Normal Regular expressions for Both latitude & longitude:
Latitude RegEx:
^(\+|-)?((\d((\.)|\.\d{1,6})?)|(0*?[0-8]\d((\.)|\.\d{1,6})?)|(0*?90((\.)|\.0{1,6})?))$
Longitude RegEx:
^(\+|-)?((\d((\.)|\.\d{1,6})?)|(0*?\d\d((\.)|\.\d{1,6})?)|(0*?1[0-7]\d((\.)|\.\d{1,6})?)|(0*?180((\.)|\.0{1,6})?))$