Jump to content

Regex for latitude and longitude


AdRock

Recommended Posts

I have found regular expressions for latitude and longitude but am not sure if it will work for the co-ords i want to give it

 

This is the latitude regex

^-?([1-8]?[1-9]|[1-9]0)\.{1}\d{1,6}

 

and the longitude

^-?([1]?[1-7][1-9]|[1]?[1-8][0]|[1-9]?[0-9])\.{1}\d{1,6}

 

What i expect to be able to validate is co-ords like this

 

50.790047                    -3.648091

-122.083739,37              37.423021

 

The bottom co-ordinates are for google HQ and the other is for devon in the UK so obviously they can vary

 

Is this going to work are is it restricting me to a limited range?

Link to comment
https://forums.phpfreaks.com/topic/98798-regex-for-latitude-and-longitude/
Share on other sites

This is quoted from where i got the regex

Description I was inspired by this regexp - Matches a whole number between 1 and 20 inclusively - because it was doing something I could not find elsewhere so this is how I expanded it to validate lat values

 

Matches 90.0, -90.9,1.0, -23.343342

Non-Matches 90, 91.0,  -945.0, -90.3422309

 

I noticed that one of the non-matches is -90.3422309 but i could very well need to allow that

The problem is that the decimal places exceed 6. This could be tweaked. Here's some code for testing your expressions:

 

<pre>
<?php

$tests = range(-200, 200);
array_push($tests, '90.000000', '-90.000000', '180.000000', '-180.000000');
sort($tests);

function rand_dec(&$test) {
	if (preg_match('/\.0+\z/', $test)) {
		return;
	}
	$rand_str = '';
	for ($i = 0; $i < 6; $i++) {
		$rand_str .= rand(0, 9);
	}
	$test .= ".$rand_str";
}

$lat_pattern = '/
	\A
	[+-]?
	(?:
		90(?:\.0{1,6})?
		|
		\d
		(?(?<=9)|\d?)
		\.
		\d{1,6}
	)
	\z
/x';

$long_pattern = '/
	\A
	[+-]?
	(?:
		180(?:\.0{1,6})?
		|
		(?:
			1[0-7]\d
			|
			\d{1,2}
		)
		\.
		\d{1,6}
	)
	\z
/x';

foreach ($tests as &$test) {
	rand_dec($test);
	echo $test,
		' :: Valid LAT: ',
		(preg_match($lat_pattern, $test) ? 'Y' : 'N'),
		' :: Valid LONG: ',
		(preg_match($long_pattern, $test) ? 'Y' : 'N'),
		'<br/>';
}

?>
</pre>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.