How to validate latitude and longitude
60,775
Solution 1
The latitude must be a number between -90 and 90 and the longitude between -180 and 180.
Solution 2
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;
Solution 3
In Kotlin we can do something like this:
fun isValidLatLang(latitude: Double?, longitude: Double?): Boolean {
return latitude?.toInt() in -90 until 90 && longitude?.toInt() in -180 until 180
}
Solution 4
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})?))$
Author by
Admin
Updated on July 09, 2022Comments
-
Admin almost 2 years
I have two UITextFields which users can enter in a latitude and longitude, these co-ordinates are then used to create a pin on an MKMapView.
I want find a way to validate whether the values they enter are actual GPS co-ordinates or just a load of rubbish. Is there any way of doing this?
-
Gajus over 10 yearsAn answer with an explanation, stackoverflow.com/a/6536279/368691. Yes, it is correct answer. However, this assumes land and sea.
-
Adi Inbar almost 10 yearsThis answer is in the Low Quality Posts review queue because it's just code with no explanation. Please improve your answer by explaining what your code does and how it answers the question. Please read this advice on answering programming questions helpfully.
-
Mehmed over 9 yearsShould we include border? (long >= -180 && long <= 180) or (long > -180 && long < 180) ?
-
Sahil Sharma about 6 years@Mehmed No. It should be (long > -180 && long < 180) AND (lat > -90 && lat < 90).
-
guissoares almost 6 years@SahilSharma Is there a reason for that? What happens if one of the coordinates happens to be exactly at one of the extremes (example: google.com.br/maps/place/…)?
-
Malik Bagwala almost 4 yearsI dont know what this achieves over the accepted answer (instead of complicating the matter)
-
Berin Loritsch about 3 yearsYes, include the border, but just understand for longitude, -180 and 180 are the same point. For Latitude, 90 is the geographic north pole and -90 is the geographic south pole.