Skip to content

Instantly share code, notes, and snippets.

@anandaroop
Last active February 12, 2023 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandaroop/a1b794559615b2bbdea097678321c93f to your computer and use it in GitHub Desktop.
Save anandaroop/a1b794559615b2bbdea097678321c93f to your computer and use it in GitHub Desktop.
Mongo radius query test
require 'mongo'
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'geotest')
points = client[:points]
geopoints = client[:geopoints]
module GeoJSON
class Feature
def initialize(geometry:, properties:)
@geometry = geometry
@properties = properties
end
def to_h
{
type: 'Feature',
geometry: @geometry,
properties: @properties
}
end
def to_json
JSON.generate(to_h)
end
def self.from_point(point:, properties:)
new(
geometry: {
type: 'Point',
coordinates: point
},
properties: properties
)
end
end
class FeatureCollection
def initialize(features:)
@features = features
end
def to_h
{
type: 'FeatureCollection',
features: @features
}
end
def to_json
JSON.generate(to_h)
end
end
end
class PointGrid
def initialize(xmin:, xmax:, ymin:, ymax:, step:)
@xmin = xmin
@xmax = xmax
@ymin = ymin
@ymax = ymax
@step = step
end
def each_point
x = @xmin
y = @ymin
while x < @xmax
while y < @ymax
yield [x.round(4), y.round(4)]
y += @step
end
y = @ymin
x += @step
end
end
def insert_geojson(collection:)
each_point do |point|
collection.insert_one({
location: {
type: 'Point',
coordinates: point
}
})
end
end
end
grid = PointGrid.new(
xmin: -118.6,
xmax: -117.85,
ymin: 33.75,
ymax: 34.35,
step: 0.02
)
geopoints.drop && grid.insert_geojson(collection: geopoints)
points_inside = geopoints.find({
"location" => {
"$geoWithin" => {
# "$center" => [[-118.24, 34.05], 25 / 111.32]
"$centerSphere" => [[-118.24, 34.05], 25 / 6378.1]
}
}
}).to_a
points_outside = geopoints.find({
"location" => {
"$not" => {
"$geoWithin" => {
# "$center" => [[-118.24, 34.05], 25 / 111.32]
"$centerSphere" => [[-118.24, 34.05], 25 / 6378.1]
}
}
}
}).to_a
features = []
points_inside.each do |point|
features << GeoJSON::Feature.from_point(
point: point[:location][:coordinates],
properties: {
id: point[:_id].to_s,
status: "inside"
}
).to_h
end
points_outside.each do |point|
features << GeoJSON::Feature.from_point(
point: point[:location][:coordinates],
properties: {
id: point[:_id].to_s,
status: "outside"
}
).to_h
end
fc = GeoJSON::FeatureCollection.new(features: features)
puts fc.to_json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment