Skip to content

Instantly share code, notes, and snippets.

@ian29
Created August 27, 2014 14:52
Show Gist options
  • Save ian29/db51041d14df046c3c2f to your computer and use it in GitHub Desktop.
Save ian29/db51041d14df046c3c2f to your computer and use it in GitHub Desktop.
scale, the z() function, zoom levels

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