Search code examples
javascriptazure-maps

Azure Maps label text that scales with the zoom level


Is it possible to create a text label that stays the same relative size compared to the map when zooming in or out? Reading the docs and looking at the symbol layer sample, it seems that this is not possible and that the label will always have the same absolute size (appearing larger when zooming out), but I'm curious whether it is possible to achieve this somehow, using some sort of undocumented feature. If not, is it possible to request this feature somewhere; or is this out of scope?


Solution

  • Yes it is possible to scale the label so that its size stays relative to some physical distance on the ground. To achieve this you need to use a style expression to scale the label size based on the maps zoom level. An interpolation expression is a good option but is a bit complicated as you need to decide how big you want the label at one zoom level, and then calculate its scaled size at a second one as it requires a minimum of two inputs. The map scales such that each zoom level covers two as much area as the one before it so an exponential interpolation works well. It does get a bit difficult when zoomed out as the size can become smaller than 1, so setting a minimum pixel size is a good option, alternative you can hide the label when outside of the desired zoom range. Here is a simple example:

    map.layers.add(new atlas.layer.SymbolLayer(datasource, null, {
        iconOptions: {
            image: 'none'
        },
        textOptions: {
            textField: "Hello World!",
            size: [
                'interpolate',
                ['exponential', 2],
                ['zoom'],
                //For all zoom levels 7 or lower, set the radius to 2 pixels.
                7, 2,
    
                //Between zoom level 7 and 22, exponentially scale the radius from 2 pixels to 50000 pixels.
                22, 50000
            ]
        }
    }));
    

    You can see a running version of this code here: https://rbrundritt.azurewebsites.net/Demos/AzureMaps/ScalingLabels.html

    I find that just adjusting the 50000 value to a different number allows you to easily scale the label to a more appropriate size while the zoom scaling seems to still work pretty good relative to the ground. Try replacing 50000 with 5000 and you will see what I mean.

    Note, if your label becomes really large when zoomed in (larger than the map canvas), the label may disappear as the center point may become out of view. There isn't much you can do about this using this approach. If you have a lot of labels and need to support this scenario, you would then need to consider creating static map tiles. That said, usually if the label is larger than the map canvas, you can't read it and its just in the way.