Search code examples
ruby-on-rails-4postgisrails-geocodergeokitrgeo

Add distance to a particular latitude/longitude position


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?


Solution

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