Skip to content

Instantly share code, notes, and snippets.

@jsanz
Created September 14, 2016 09:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanz/4564f98c197106432f1b8bf8c9d0230e to your computer and use it in GitHub Desktop.
Save jsanz/4564f98c197106432f1b8bf8c9d0230e to your computer and use it in GitHub Desktop.
SQL: ring buffers with several distances

Query to produce a series of rings using buffers:

  • First you get a generate_series with the number of rings you want to produce
  • Then produce the 80km buffers multiplying by the radius for a number of cities
  • Finally use the lag function to remove for every ring the previous one so you get the ring

WITH rings AS (
SELECT generate_series(1, 5) as radius
), circles AS (
SELECT
cartodb_id,
radius,
ST_Transform(
ST_Buffer(
the_geom::geography,
radius * 80000
)::geometry
,3857
) AS the_geom_webmercator
FROM populated_places, rings
WHERE NAME in
('Madrid','Helsinki','Warsaw',
'London','Trondheim')
)
SELECT
cartodb_id,
radius,
CASE
WHEN radius = 1
THEN the_geom_webmercator
ELSE
ST_Difference(
the_geom_webmercator,
lag(the_geom_webmercator) OVER (PARTITION BY cartodb_id ORDER BY radius)
)
END AS the_geom_webmercator
FROM circles
/** choropleth visualization */
@color0: #fef6b5;
@color1: #ffd08f;
@color2: #ffa679;
@color3: #f67c78;
@color4: #e15383;
#populated_places{
polygon-fill: #FFFFB2;
polygon-opacity: 0.8;
line-color: #FFF;
line-width: 2.5;
line-opacity: 1;
}
#populated_places [ radius = 5] {
polygon-fill: @color4
}
#populated_places [ radius = 4] {
polygon-fill: @color3
}
#populated_places [ radius = 3] {
polygon-fill: @color2
}
#populated_places [ radius = 2] {
polygon-fill: @color1
}
#populated_places [ radius = 1] {
polygon-fill: @color0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment