rgeo/rgeo-geojson

How to intersect two geojson files?

FergusDevelopmentLLC opened this issue · 2 comments

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:
https://gist.github.com/FergusDevelopmentLLC/2a4314be6d43ecda163979127d71caf5

outline.geojson contains a single polygon
here is a gist of my outline.geojson: https://gist.github.com/FergusDevelopmentLLC/1a7ae0708d7a8ee9e113f13654d39a4e

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 <main>': undefined method intersection' for #RGeo::GeoJSON::FeatureCollection:0x294ac44 (NoMethodError)

the only thing I can find remotely similar is:
#34

Hi @FergusDevelopmentLLC,

Are you using rgeo with the geos c++ library installed ? This makes a huge difference since most of rgeo methods come from this library. If not, we'll soon upgrade rgeo to a version which includes the method Polygon#contains? which can solve your issue. Here's a fixed and commented version of your code that works with rgeo master or a code base on which RGeo::Geos.supported? returns true:

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.geojsn is a feature collection containing only one feature that is
# interesting. Hence the `.first`
outline = RGeo::GeoJSON.decode(outline_str, json_parser: :json).first
puts outline

# To do geometry computation, we do not want to use the GeoJSON object but its
# underlying geometry.
outline_geometry = outline.geometry

contained_points = points.select do |point|
  outline_geometry.contains?(point.geometry)
end

puts contained_points

Does this answer your question ?

Closing due to inactivity, this will be better handled after #53