Skip to content

Instantly share code, notes, and snippets.

@dakur
Last active December 14, 2017 09:31
Show Gist options
  • Save dakur/c57140bbf211dd8cc670 to your computer and use it in GitHub Desktop.
Save dakur/c57140bbf211dd8cc670 to your computer and use it in GitHub Desktop.
Regular expression for checking GPS coordinates

Update: In the end, I've decided to validate against some map API, because there are too many cases which this piece of regexp can not cover.


JavaScript

^(N|S)?\s*(\d*[.])?\d+(\u00b0\s*)?((\d*[.])?\d+((\u0022)|((\u0027\s*)?)?((\d*[.])?\d+?(\u0022)?)?))?[\s\u002c]+(W|E)?\s*(\d*[.])?\d+(\u00b0\s*)?((\d*[.])?\d+((\u0022)|((\u0027\s*)?)?((\d*[.])?\d+(\u0022)?)?))?$

Use flag /i
Live demo: https://regex101.com/r/kI5tZ7/7

PHP

^(N|S)?\s*(\d*[.])?\d+(\x{00b0}\s*)?((\d*[.])?\d+((\x{0022})|((\x{0027}\s*)?)?((\d*[.])?\d+?(\x{0022})?)?))?[\s\x{002c}]+(W|E)?\s*(\d*[.])?\d+(\x{00b0}\s*)?((\d*[.])?\d+((\x{0022})|((\x{0027}\s*)?)?((\d*[.])?\d+(\x{0022})?)?))?$

Use flag /i
Live demo: https://regex101.com/r/mF8fD8/6

Supported formats

(N|S) D(°) (W|E) D(°)
(N|S) D° M(') (W|E) D° M(')
(N|S) D° M' S(") (W|E) D° M' S(")
(N|S) D° S" (W|E) D° S"

  • Latitude and longitude parts can be separated by comma and/or whitespace(s).
  • Formats can be combined.
  • D, M and S support floating numbers.

Known bugs

  • N 10° 10.10.10" should not be accepted
  • NSWE at the end is not accepted
  • +/- is not accepted
  • different apostrophes and quotes than U+0022 (") and U+0027 (') are not accepted
  • so many others...

In case you found some other bugs, please let me know.

Last update: 04/06/2016

Similar gist: https://gist.github.com/moole/3707127

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment