Forum OpenACS Q&A: Re: Closest Address Calculation

Collapse
Posted by Tom Ayles on

Ignoring any functions, if you have a table definition like:

create table foo_addrs (
  str_num integer,
  str_name varchar(100),
  x float,
  y float
);

Then a query like the following should do the trick (where x0 and y0 are the variables containing the x-y coordinates of the location you are searching from):

select
  sqrt(distance) AS distance,
  str_num || ' ' || str_name AS address
from
  (select (:x0 - x)^2 + (:y0 - y)^2 as distance, *
   from foo_addrs order by distance limit 1) as r

This is all valid for PostgreSQL. I believe PostgreSQL also has a spatial coordinate type designed for this kind of thing.

HTH,
Tom