So i have a model that saves latlong data. And i want to make a methode that i give a point_x, point_y , and sees if my Location model has a point that is near 500m or less.
Here is an exemple of points:
Location.longlat.x = 43.3233
Location.lonlat.y = 23.3233
point_x = 32.3233
point_y = 23.323
I store those longlat coordinates using postgis for my model. So far i know its save them as spherical points and are º. So is there a method to define them as plane points and calculate if they are close to 500m or less ?
Edit: This is how i store longlat coordinates in my model:
t.geography "longlat", limit: {:srid=>4326, :type=>"st_point", :geographic=>true}
EDIT: script that im trying to use
ForecastLocation.all.each do |forecast_location|
ForecastLocation.where("ST_Distance_Sphere(ST_MakePoint(
{forecast_location.longlat.x},#{forecast_location.longlat.y}),
ST_MakePoint(#{circle_x},#{circle_y})<500")
ForecastLocation = is model name
longlat= column defined above , saves x,y
circle_x
circle_y = variables that makes the main point, and compare this one to all my ForecastLocation.longlat
What im tring is to do same thing as in the answer with the select , but just to have all objects that are closer than 500m of circle
CodePudding user response:
You can get the distance (in meters) between two points on a sphere via ST_DistanceSphere
:
SELECT ST_DistanceSphere(
ST_MakePoint(43.3233, 23.3233),
ST_MakePoint(32.3233, 23.323)
);
--> 1122927.11865462
To select all locations within 500 meters, you could use something like this:
SELECT *
FROM locations
WHERE ST_DistanceSphere(
ST_MakePoint(x, y),
ST_MakePoint(32.3233, 23.323)
) <= 500;
where locations
is your table and x
/ y
are your lat / long columns.