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
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

Link to comment
Share on other sites

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>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.