1

I have a table in postgresql 9.2 that stores the latitude and longitude of locations as integer values.

I intend to do something like when a user searches for a location, he also gets information on other locations that are within a 7 mile radius of that searched location.

How do i use postGIS for this since i am new to it. Any idea.?

1 Answer 1

3

You'll actually want to store the latitude and longitude as a point.

CREATE TABLE postal_codes
(
  zip character varying(7) NOT NULL,
  state character(2) NOT NULL,
  city character varying(50) NOT NULL,
  geoloc geography(Point,4326) NOT NULL
);
INSERT INTO postal_codes
VALUES (
    '35004', 'AL', 'Moody',
    ST_GeographyFromText('SRID=4326;POINT(-86.50249 33.606379)') -- lon lat
);

You can then get all points within a certain distance using STDWithin.

SELECT geoloc
FROM postal_codes
WHERE ST_DWithin(
    geoloc,                            -- The current point being evaluated
    'thegeolocyoustoredawaysomewhere', -- the location of the person
                                       -- you're giving info to
    7 * 1.6 * 1000                     -- Miles to meters
);

Or:

SELECT geoloc
FROM postal_codes
WHERE ST_DWithin(
    geoloc,
    (
        SELECT geoloc
        FROM postal_codes
        WHERE zip = '12345'
    ),
    7 * 1.6 * 1000
);

To boost performance a bit for other kinds of queries (not any seen here), use a GiST index:

CREATE INDEX geoloc_idx
ON postal_codes
USING gist (geoloc);
Sign up to request clarification or add additional context in comments.

4 Comments

What about performance? I assume the user Neville is storing lat/lng as integers to increase performance (maybe because of using modest hardware)
On my Pentium II 233 MHz server (that's right, server) a similar query will take about 30 seconds to complete. About 5 seconds on my modern workstation.
That is just the point. I am serving the site www.mapatia.com with an Atom N550. This server has a few millions of geopoints stored on a Postgresql table and I also manage lat/lng as integers just to get faster index operations. I need response times in the range of 100 ms or faster.
You can generate a 3 column table (geo1, geo2, distance) to cache that kind of data to get sub-100 ms rather than doing the same calculation repeatedly. Or, parital indexes (USING gist (ST_DWithin(geo1, geo2, distance))), or partition your tables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.