Rails regex for checking latitude longitude in Google Maps

I am trying to make a validates_format_oflatlng object that is returned from the Google Maps API. My map is configured perfectly, so when I click on a point on the map, it fills the text box with latlng (which looks like this: 46.320615137905904, 9.400520324707031). I save this value as a string in db (which I then parse to put markers on the map later), but I need to check the sting format as two floats (positive or negative) with a comma between them.

I know that this is possible with a regex, but for my life it was not possible to compute a string of regexes to make it work.

Any help would be appreciated super! Thank you Jeff

+3
source share
4 answers

/^-?\d+\.\d+\,\s?-?\d+\.\d+$/

  • ^ corresponds to the beginning
  • $ matches end of line
  • -? matches an optional minus sign
  • \d+ matches 1 or more digits
  • \.computes a point (you need to avoid it because it .matches any character)
  • \s? matches an optional space

You might want to accept spaces at the beginning or end:

/^\s*-?\d+\.\d+\,\s?-?\d+\.\d+\s*$/

+8
source

I check this way:

var ck_lat = /^-?([1-8]?\d(?:\.\d{1,})?|90(?:\.0{1,6})?)$/;
var ck_lon = /^-?((?:1[0-7]|[1-9])?\d(?:\.\d{1,})?|180(?:\.0{1,})?)$/;
var lat = 89.320615;
var lon = 179.400520;

if(ck_lat.test(lat) && ck_lon.test(lon)) {
    //Was a valid latitude and longitude pair :)
}

This is under development, but it works fine, here is a link for testing as regexp:

Check Latitude: http://rubular.com/r/vodC5TW3lG

Longitude Check: http://rubular.com/r/3LIIcjFEQT

EDIT: , -90/-180, , :) .

+9

Regex, split

latitude, longitude = latlong.split(',')

.

+6

-90 90 -180 180

, , , 4-6 ( google api 6 )

: /^(-?(90\.0{4,6})|([0-8]\d{0,1})\.\d{4,6})$/

http://rubular.com/r/UpY74Y4fuG

: /^(-?((180)\.0{4,6})|((1[0-7][0-9])|([0-9]\d{0,1}))\.\d{4,6})$/

http://rubular.com/r/OQ0KS7puhv

+1

Source: https://habr.com/ru/post/1753264/


All Articles