Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails regex for validation of Google Maps latitude longitude

I'm trying to do a validates_format_of on the latlng object that is passed back from Google Maps API. I've got the map set up perfectly so that when I click on a point in the map it fills in a text-field with the latlng (which looks like this: 46.320615137905904, 9.400520324707031). I'm storing this value as a string in the db (which I then parse out to place markers on the map later) but I need to validate the format of the sting as two floats (positive or negative) with a comma in between.

I know that this is possible with regex but for the life of my haven't been able to figure out the regex string to get it working.

Any help would be super appreciated! Thanks! Jeff

like image 424
erskingardner Avatar asked Nov 28 '22 04:11

erskingardner


1 Answers

I'm validating 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 on development stage, but it works ok, here is the link for testing both regexp:

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

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

EDIT: Thanks to Tim Kelly for the improvement, this one catches -90 / -180, i think now is complete :) Links and code edited.

like image 85
mzalazar Avatar answered Nov 30 '22 23:11

mzalazar