Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate latitude and longitude

People also ask

How do you know if latitude and longitude are valid?

Each line contains a pair of co-ordinates which possibly indicate the latitude and longitude of a place. The latitude and longitude, if present will always appear in the form of (X, Y) where X and Y are decimal numbers. For a valid (latitude, longitude) pair: -90<=X<=+90 and -180<=Y<=180.

What are valid latitude and longitude values?

Latitude and longitude are a pair of numbers (coordinates) used to describe a position on the plane of a geographic coordinate system. The numbers are in decimal degrees format and range from -90 to 90 for latitude and -180 to 180 for 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.

  1. Latitude must be a number between -90 and 90
const isLatitude = num => isFinite(num) && Math.abs(num) <= 90;
  1. 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})?))$

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
}