The following functions will validate latitude and longitude data. The functions support a number of geo-related articles on our website .
1
<?php
2
/*
3
Validate Latitude and Longitude
4
http://www.beliefmedia.com/code/php-snippets/validate-latitude-longitude
5
*/
6
7
function beliefmedia_valid_lat($latitude) {
8
9
}
10
11
function beliefmedia_valid_lng($longitude) {
12
return (preg_match("/^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{0,6}$/", $longitude)) ? true : false;
13
}
Returns false
if the value does not match.
The function validates again 6 decimal points (which you may obviously change). To force the six digits, and to further clean the input data, using $latitude = number_format($latitude, 6);
(for both latitude and longitude) before validation may assist. In addition to truncating the decimals (or adding them), the function acts a little like the abs()
function in that it'll remove invalid characters. Because the decimals are required, the function will also add them if omitted.
We've also used the following expressions... essentially achieving the same thing.
1
<?php
2
/*
3
Validate Latitude and Longitude
4
http://www.beliefmedia.com/code/php-snippets/validate-latitude-longitude
5
*/
6
7
function beliefmedia_valid_lat($latitude) {
8
return preg_match('/^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/', $latitude);
9
}
10
11
function beliefmedia_valid_lng($longitude) {
12
return preg_match('/^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/', $longitude);
13
}