title: How to search in a radius using Postgres extension?
body: <p>Finding distances on the surface of the earth means using Great Circle distances, worked out with the Haversine formula, also called the Spherical Cosine Law formula.</p>
  
  <p>The problem is this: Given a table of locations with latitudes and longitudes, which of those locations are nearest to a given location?</p>
  
  <p>I have the following query:</p>
  
  <pre><code> SELECT z.id,
          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 doorbots as z
   JOIN (   /* these are the query parameters */
      SELECT 34.0480698 AS latpoint, -118.3589196 AS longpoint,
             2 AS radius,  111.045 AS distance_unit
        ) AS p ON 1=1
   WHERE z.latitude between ... and 
         z.longitude between ...
  </code></pre>
  
  <p>How to use <a href="https://www.postgresql.org/docs/8.4/static/earthdistance.html" rel="nofollow noreferrer"><code>earthdistance</code></a> extension to change my complicated formula in the query?</p>
  
  <p>Is it equivalent change?</p>
  
  <pre><code>SELECT z.id,
         z.latitude, z.longitude,
         p.radius,
         round(earth_distance(ll_to_earth(p.latpoint, p.longpoint), ll_to_earth(z.latitude, z.longitude))::NUMERIC,0) AS distance
   FROM doorbots as z
   JOIN (   /* these are the query parameters */
      SELECT 34.0480698 AS latpoint, -118.3589196 AS longpoint,
             2 AS radius,  111.045 AS distance_unit
        ) AS p ON 1=1
   WHERE z.latitude between ... and 
         z.longitude between ...
  </code></pre>