Quentin Gaultier
Quentin Gaultier

Reputation: 318

rgeo: distance calculation between a point and a line

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 ?

Upvotes: 1

Views: 338

Answers (1)

old_dd
old_dd

Reputation: 175

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

Upvotes: 1

Related Questions