1

Rails 4 + Postgres. New to geospatial. Happy to accept solutions that involve RGeo, Geokit, Geocoder, or any other gem that helps solve this issue.

Model contains two fields latitude and longitude.

I have an offset attribute that contains a distance in meters and an orientation attribute that contains one of the 4 cardinal directions (N, E, W, S).

Example: offset: 525.5 orientation: W

What's a standard way of adding the offset distance to the lat-long position, to give me a new lat-long pair as the result of the distance addition?

changingrainbows
  • 2,551
  • 1
  • 28
  • 35

2 Answers2

2

For small offsets such as a few hundred metres:

You can handle the N&S orientations knowing that:

R * (lat1-lat2)= NorthSouth distance

where R is the Earth radius (6335km).

You can handle the E&W orientations knowing that:

R * cos(lat)* (lon1-lon2) = EastWest distance.

I'm sorry, I don't speak Ruby, but it should be pretty easy to translate this pseudo-code:

R=6335000         // This is in metres
PI=3.14159265     // Your compiler may have a better constant/macro
if(orientation is North or orientation is South)
  x = offset * 180 / (PI * R)
  if(orientation is South)
     x = -x
  endif
  newLatitude = latitude + x
else
  x = offset * 180 / (PI * R * cos(lat))
  if(orientation is West)
     x = -x
  endif
  newLongitude = longitude + x
endif
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Did this help/solve your question? Could you accept if so, please? Or say what's wrong with it so I can assist further? – Mark Setchell Nov 21 '13 at 10:23
  • Hi Mark... I think your solution could work, within the assumptions you defined (offset size, etc.), but I didn't try it because of the assumptions. I find that folks who've written libraries like PostGIS, RGeo, etc. account for generic precisions and I always prefer to piggy-back on their expertise rather than handrolling with assumptions. Solution seems reasonable though! – changingrainbows Nov 25 '13 at 16:33
0

It took a little bit of digging, and it turns out that there is a singular-ish library function (accounting for curvature, geometric, projection, location & mathematical assumptions) that helps add a distance to a specific surface position.

Function: ST_Project

Used below:

SELECT ST_AsGeoJSON(ST_Project('POINT(longitude latitude)'::geography, offset, radians(orientation)))

It's from PostGIS and therefore useable in Ruby/Rails, although not yet as native Ruby objects (gems haven't wrapped it yet), but as a PostGIS query instead.

offset is in meters. orientation is in degrees ('N'=0, 'E'=90, etc.)

Hopefully, this solution helps others looking for the same thing.

changingrainbows
  • 2,551
  • 1
  • 28
  • 35