1

I am working on a hotel application (using ruby on rails), and I am trying to calculate the distance between an hotel and the sea.

I have gathered the geometry of the shoreline points in a geojson file and I am now trying to calculate the distance using the rgeo gem.

My findings are the following:

when using a simple_mercator_factory, I obtain an wrong value and when using a spherical_factory the distance between 2 point is correct, but I calculating the distance between a point and a line yields an error.

How can I calculate this distance ?

Quentin Gaultier
  • 279
  • 6
  • 16
  • There're several ways, by gem or pure Ruby. You could just check the question https://stackoverflow.com/questions/12966638 – eux Apr 12 '23 at 10:42
  • this answer is for the distance between 2 points. I need the shortest distance between a point and a line – Quentin Gaultier Apr 12 '23 at 10:49
  • Oh, I see, could you give some example data of "the geometry of the shoreline points"? – eux Apr 13 '23 at 01:46
  • And more detail may be helpful: how did you use simple_mercator_factory?What's the error message? – eux Apr 13 '23 at 01:49

1 Answers1

0

Try using geographic_factory which uses spherical calculations and can handle both point-to-point and point-to-line distance calculations.

factory = RGeo::Geographic.spherical_factory(srid: 4326)

Parse the shoreline points from the GeoJSON file and convert them to RGeo objects using the geographic_factory:

shoreline_geojson = File.read('path/to/your/geojson/file')
shoreline = RGeo::GeoJSON.decode(shoreline_geojson, json_parser: :json, geo_factory: factory)

Create an RGeo point for the hotel location using the geographic_factory:

hotel_location = factory.point(hotel_longitude, hotel_latitude)

Calculate the minimum distance between the hotel location and the shoreline points:

min_distance = shoreline.points.map { |point| hotel_location.distance(point) }.min

Now, min_distance will hold the shortest distance between the hotel and the shoreline in meters.


edit: you'll need to add rgeo-geojson

gem 'rgeo-geojson'
bundle install
old_dd
  • 135
  • 2
  • 13