Forum OpenACS Q&A: Re: Closest Address Calculation

Collapse
Posted by Sam Dau on
Thanks for the response and code modification.
It seems to be having problem with certain aspects of it.
For instance, looking at the table structure I posted earlier,
the current code I am using looks like this:

select
  sqrt(distance) AS distance,
  str_num || ' ' || name AS address
from
  (select (:x(the_geom)0 - x(the_geom))^2 + (:y(the_geom)0 - y(the_geom))^2 as distance, *
  from address order by distance limit 1) as r

Notice the the syntax x(the_geom)

As you know, in PostGIS we get the x and y of each point shape using the x(geometry) and y(geometry) functions.
However, in our database, the geometry is already in the field called the_geom, so to get the x and y for each point we use it like this: x(the_geom) and y(the_geom).

The question becomes, how can I blend your part of the script: select (:x0 - x)^2 + (:y0 - y)^2 as distance into this: x(the_geom) and y(the_geom)?
I tried (:x0(the_geom) - x(the_geom))^2 + (:y0(the_geom) - y(the_geom))^2 as distance but it is error-ying out on both the :(colon) and the 0.

I must point out that if I use the code this way:

select
  sqrt(distance) AS distance,
  str_num || ' ' || name AS address
from
  (select (x(the_geom) - x(the_geom))^2 + (y(the_geom) - y(the_geom))^2 as distance, *
  from address order by distance limit 1) as r

(Without the colon and 0), it does return an address but I am afraid something significant is missing.

Any further assistance would be appreciated.

Collapse
Posted by Tom Ayles on
I figured you were running this query through OpenACS, what with this being the OpenACS forums 'n' all 😉. The syntax :x0 specifies a bind variable - the value of the variable x0 is substituted into the query in that position by the database driver. So if you want to run the query directly, substitute the :x0 and :y0 parts with the X-Y coordinates of the point you are measuring from. The maths behind this is just Pythogoras theorem - a quick google would find about 34,500 pages if you want to read more.