Search code examples
rubygeojsonintersectionrgeo

How to do an intersection of geojson with rgeo?


I am new to ruby and experimenting with rgeo.

I have 2 geojson files: points.geojson contains a number of points here is a gist of points.geojson

outline.geojson contains a single polygon here is a gist of my outline.geojson:

I want the intersection (points that are contained within outline)

Here is what I am trying...

require 'rgeo'
require 'rgeo/geo_json'

points_str = File.read("points.geojson")
points = RGeo::GeoJSON.decode(points_str, json_parser: :json)
puts points

outline_str = File.read("outline.geojson")
outline = RGeo::GeoJSON.decode(outline_str, json_parser: :json)
puts outline

puts points.intersection outline

The error I get: intersection.rb:12:in ': undefined method intersection' for #RGeo::GeoJSON::FeatureCollection:0x294ac44 (NoMethodError)


Solution

  • The issue with your code is that RGeo::GeoJSON.decode doesn't return geometries, but an instance of RGeo::GeoJSON::FeatureCollection.

    You first have to extract the relevant geometries, i.e. the array of points and the polygon, respectively.

    This snippet does what you want:

    require 'rgeo'
    require 'rgeo/geo_json'
    
    points = RGeo::GeoJSON
      .decode(File.open('points.geojson'))
      .map(&:geometry)
    puts points
    
    polygon = RGeo::GeoJSON
      .decode(File.open("outline.geojson"))
      .first
      .geometry
    puts polygon
    
    contained_points = points.select { |p| p.within?(polygon) }
    puts contained_points