Skip to content

Instantly share code, notes, and snippets.

@thadk
Last active August 14, 2018 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadk/d9001c8493925de6da327ded6da2febf to your computer and use it in GitHub Desktop.
Save thadk/d9001c8493925de6da327ded6da2febf to your computer and use it in GitHub Desktop.
Following Paul Ramsey's blog post about equal area subdivisions in Carto

Following Paul Ramsey's blog in Carto

CREATE TABLE peru AS
	SELECT * FROM countries
    WHERE name LIKE 'peru'
CREATE TABLE peru_pts AS
  SELECT 
  	ST_SetSRID((ST_Dump(ST_GeneratePoints(the_geom, 500))).geom,4326) AS the_geom,
  	ST_Transform(ST_Buffer(the_geom,0.001), 3857) as the_geom_webmercator
  FROM peru
  WHERE name LIKE 'peru'
  select cdb_cartodbfytable('peru_pts')

Read more about this at: https://github.com/CartoDB/cartodb/wiki/creating-tables-though-the-SQL-API

  CREATE TABLE peru_pts_clustered AS
  SELECT 
  	the_geom, 
	the_geom_webmercator,
  	ST_ClusterKmeans(the_geom, 10) over () AS cluster
  FROM peru_pts;
  CREATE TABLE peru_centers AS
	SELECT cluster,
		ST_Centroid(ST_collect(the_geom)) AS the_geom FROM peru_pts_clustered
  	GROUP BY cluster
    select cdb_cartodbfytable('peru_centers')
CREATE TABLE peru_voronoi AS
  SELECT (ST_Dump(ST_VoronoiPolygons(ST_collect(the_geom)))).geom AS the_geom
  FROM peru_centers;
      select cdb_cartodbfytable('peru_voronoi')
CREATE TABLE peru_divided AS
  SELECT ST_Intersection(a.the_geom, b.the_geom) AS the_geom
  FROM peru a
  CROSS JOIN peru_voronoi b;
      select cdb_cartodbfytable('peru_divided')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment