Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dsandip/8f85439eb59adc9c659bafe9d0106c00 to your computer and use it in GitHub Desktop.
Save dsandip/8f85439eb59adc9c659bafe9d0106c00 to your computer and use it in GitHub Desktop.
Custom functions: sample SETOF table and custom PostGIS function
-- SETOF table
CREATE TABLE user_landmarks (
user_id INTEGER,
location GEOGRAPHY(Point),
nearby_landmarks JSON
);
-- function returns a list of landmarks near a user based on the
-- input arguments distance_kms and userid
CREATE FUNCTION search_landmarks_near_user(userid integer, distance_kms integer)
RETURNS SETOF user_landmarks AS $$
SELECT A.user_id, A.location,
(SELECT json_agg(row_to_json(B)) FROM landmark B
WHERE (
ST_Distance(
ST_Transform(B.location::Geometry, 3857),
ST_Transform(A.location::Geometry, 3857)
) /1000) < distance_kms
) AS nearby_landmarks
FROM user_location A where A.user_id = userid
$$ LANGUAGE sql STABLE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment