Find all points within a polygon

82 views
Skip to first unread message

Seth Siegler

unread,
Jan 26, 2017, 5:11:32 PM1/26/17
to RGeo-Users
Hi everyone,

I'm new to rgeo but looking to do something that I thought would be a little easier to find! Appreciate the help of the community, in advance. I'm using rails 4.2 and the rgeo gem. 

I have a rails model (MyModel) that has a postgis column "point" column called latlon. 

I'm looking to find all MyModel records that have a latlon point within a given polygon. 

I'm creating a polygon from a linestring without issue like this: 

    factory = RGeo::Geographic.spherical_factory(:srid => 4326)
    a
= []
    points
= params[:polygon]
    points
.each do |point|
      a
<< factory.point(point[0],point[1])
   
end
    linestring
= factory.line_string(a)
    poly
= factory.polygon(linestring)

What I would now like to get some help with is crafting the query that will find all MyModel instances that have a latlon point within this given polygon. 

Thanks in advance! 

Barrett Clark

unread,
Jan 27, 2017, 1:14:59 PM1/27/17
to RGeo-Users
It sounds like ST_CONTAINS or ST_OVERLAPS may be the PostGIS functions that you're looking for (http://postgis.net/docs/manual-1.4/ST_Contains.html, http://postgis.net/docs/ST_Overlaps.html).

I usually write these sorts of queries using the PostGIS geospatial functions directly, but it looks like you can also use them in a more Rails-friendly way: http://stackoverflow.com/questions/18264457/postgiss-st-overlaps-method-is-only-returning-results-overlapping-the-linearrin

Specifically,
MyModel.where{st_overlaps(:latlng_field, poly)}
HTH,
Barrett
Reply all
Reply to author
Forward
0 new messages