Monday, September 20, 2010

Voronoi Diagrams in PostGIS

(Update: A faster version of this code is here: Faster Voronoi Diagrams in PostGIS)

I found myself in a situation where I needed to create a Voronoi diagram from a set of points using PostGIS. This isn't built in, but a little googling turned up a function written by Mike Leahy. I adapted it and made it a bit more generic, so it shouldn't require any editing to make it work for many (most?) cases.

Call it as: select * from voronoi(table_name text,table_primary_key text,geom_col text)  as (id id_type, the_geom geometry)


For example:



select * from voronoi('oregon_cities', 'id', 'the_geom_centroids') as (id integer, the_geom geometry);


The 'as' clause is required because we don't know and don't want to assume what type your primary key might be. But, because we're returning a record type, the query planner wants to know what type to expect. If you're always using the same type, say an integer for your primary key, then it would be easy to define a type thusly:


create type my_type as (id integer, the_geom geometry);


Then change the code at line 24 from 'rec record;' to 'rec record%my_type;' and you will no longer need the 'as' clause.


Code at this URL: http://db.tt/aInuiJ2.  Enjoy.