Skip to content

Instantly share code, notes, and snippets.

@Rub21
Forked from ian29/scale.md
Last active August 29, 2015 14:15
Show Gist options
  • Save Rub21/dd767992ec8e6692ca82 to your computer and use it in GitHub Desktop.
Save Rub21/dd767992ec8e6692ca82 to your computer and use it in GitHub Desktop.

scale, and selecting specific zoom levels

Mapnik is very smart about converting map scale to zoom level. As a secret/power user feature, Mapnik exposes a !scale_denominator! variable that changes according to the zoom level and + latitude of the vector tile being rendered. Read about the Mapnik's !scale_denominator! variable here.

With some postgres magic, the !scale_denominator lets us control which features appear and disappear, within a layer.

Concretely this is a two-part process. First you will need to load the following z() function into your PostGIS database:

CREATE OR REPLACE FUNCTION public.z(scaledenominator numeric)
 RETURNS integer
 LANGUAGE plpgsql IMMUTABLE
AS $function$
begin
    -- Don't bother if the scale is larger than ~zoom level 0
    if scaledenominator > 600000000 then
        return null;
    end if;
    return round(log(2,559082264.028/scaledenominator));
end;
$function$;

The z() function takes Mapnik's !scale_denominator! as a parameter (again, which depends on the vector tile being rendered) and returns a zoom level. This allows us to construct queries/layers in Mapbox Studio like this:

( select
    some, attributes,
    geom_generalized
  from your_table
  where z(!scale_denominator!) in (10,11,12)
  union ALL
  select
    some, attributes,
    geom_not_generalized
  from your_table
  where z(!scale_denominator!) >= 13
) as data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment