10. To implement a distance converter module
moduleDistanceConverter
#...
#ConvertLatitudedistancefromKilometerstoDegrees
defto_deg_lat(km:,lat:45)
km/ONE_LAT_DEGREE[deg_approx_lat(lat)]
end
#ConvertLatitudedistancefromDegreestoKilometers
defto_km_lat(deg:,lat:45)
deg*ONE_LAT_DEGREE[deg_approx_lat(lat)]
end
#ConvertLongitudedistancefromKilometerstoDegrees
defto_deg_lng(km:,lat:45)
km/ONE_LNG_DEGREE[deg_approx_lat(lat)]
end
#ConvertLongitudedistancefromDegreestoKilometers
defto_km_lng(deg:,lat:45)
deg*ONE_LNG_DEGREE[deg_approx_lat(lat)]
end
private
#...
end
10 / 27
11. All is well, except...
This converter is Ruby. What if we need to
calculate distances in an SQL query?
11 / 27
12. A naive version
SELECT(sqrt((43.1234-latitude)^2+(23.1234-longitude)^2))ASdist
FROMareas;
That's just the linear distance between two points in a plane, so it's correct
with our assumtion when in a small city?
But the problem is it is using degrees which is a bigger problem the closer
we are to the poles.
One longitude degree will be worth less kilometers than a latitude degree.
So, what now?
12 / 27
17. PostGIS version of the query
SELECTST_Distance_Sphere(
ST_MakePoint(43.1234,23.1234),
ST_MakePoint(latitude,longitude)
)ASdist
FROMareas;
For the example, the straight line distance with our Ruby converter: 4.5 km
PostGIS result: 6.5 km
Wat
17 / 27