PostGIS: Calculate Distance Between ZIP Codes
Friday, November 14th, 2008Recently, I’ve been playing around with PostGIS (that’s geographic information system). The function, distance_sphere (or ST_distance_sphere, depending on the version), is of particular interest to me. Here’s what the documentation has to say about it:
“ST_distance_sphere(point, point), Returns linear distance in meters between two lat/lon points. Uses a spherical earth and radius of 6370986 meters. Faster than distance_spheroid(), but less accurate. Only implemented for points.”
This function is especially useful for calculating the approx. distance between zip codes. Lets say you have a table like this:
CREATE TABLE zip (
zip CHAR(5) NOT NULL PRIMARY KEY,
latitude FLOAT8 NOT NULL,
longitude FLOAT8 NOT NULL
);
You could simply add a new column like so:
ALTER TABLE zip ADD COLUMN geom GEOMETRY;
Then populate the new column:
UPDATE zip SET geom = makepoint(longitude, latitude);
The function distance_sphere, calculates the distance in meters. In order to convert the result to miles, it needs to by multiplied by 1609.344. Lets say, you want to get all zip codes within 15 miles another zip code, say 10001. You could simply do:
SELECT zip FROM zip WHERE
distance_sphere(geom,
(SELECT geom FROM zip WHERE zip = '10001'))
<= (15 * 1609.344);
There doesn’t seem to be a way to use an index to speed the query up, but it is still significantly faster than other methods. On the application side, you could use something like Memcached to cache the results, if applicable.
There are more accurate ways to find the distance between lat/lon points, however, they also require more work, and are slower.
