Given a table of locations with latitudes and longitudes, which of these places is closest to a given location?
Of course, finding distances on the surface of the earth means using the distances of the Great Circle developed with the Haversin formula, also called the spherical cosine formula.
I have the following code:
SELECT zip, latitude, longitude, distance FROM ( SELECT z.zip, z.latitude, z.longitude, p.radius, p.distance_unit * DEGREES(ACOS(COS(RADIANS(p.latpoint)) * COS(RADIANS(z.latitude)) * COS(RADIANS(p.longpoint - z.longitude)) + SIN(RADIANS(p.latpoint)) * SIN(RADIANS(z.latitude)))) AS distance FROM zip AS z JOIN ( SELECT 42.81 AS latpoint, -70.81 AS longpoint, 50.0 AS radius, 111.045 AS distance_unit ) AS p ON 1=1 WHERE z.latitude BETWEEN p.latpoint - (p.radius / p.distance_unit) AND p.latpoint + (p.radius / p.distance_unit) AND z.longitude BETWEEN p.longpoint - (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) AND p.longpoint + (p.radius / (p.distance_unit * COS(RADIANS(p.latpoint)))) ) AS d WHERE distance <= radius
Is there a way to improve the performance of this request?
Do I need to use PostGIS to improve it, or just a wrapper for my haversine formula?
performance postgresql gis location
user6611764
source share