Saturday, October 7, 2017

Angular Carto: Compound basemaps

This post is part of a series covering how to create reusable Carto map components. Read the introduction to learn why one would even want to do such a thing. The previous post in the series was voluminous, so I will change things up and describe a minor enhancement to basemap switching: basemaps that consist of more than one tile layer. This is particularly useful for adding labels to a basemap.

Enhancing the basemap prototype

This post builds off of the previous post on basemap selection. I will describe how specific components will change to accommodate multiple tile layers in a basemap. You may find it helpful to read the previous post to understand how the other components work.

First, consider the basemap prototype that requires exactly one tile layer. Its public interface exposes addToMap() and removeFromMap() methods.

Accommodating multiple tile layers in the basemap is as simple as adding a for loop to both methods. Note that after each tile layer is added to the map there is the invocation of setZIndex(layer.zIndex). Leaflet relies on a z-index to specify the order in which layers are rendered. The appropriate z-index is stored in the zIndex property of each layer.

Tweaking the basemap() function

Next, consider the basemap() factory function. Its parameters are the Carto/Leaflet map, a label to use in the user interface, and the tile layer to encapsulate, and creates a new object from the basemap prototype.

Accommodating multiple tile layers in the basemap() factory is as simple as allowing the layers parameter to be either a single tile layer or an array of tile layers. First, the function checks whether the layers argument is an array; if it is not, it converts it to an array with 1 element (lines 40–42). Next, it sets a zIndex property on each layer in ascending order relative to their position in the layers argument. This means that each element in the layers array will be drawn on top of all previous elements in the array (lines 43–45).

The list of basemaps

Now that our basemap prototype and factory can handle multiple tile layers, let’s throw some labels on top of a Google imagery layer. Carto hosts a variety of label-only layers, so we’ll use one of those. Thanks to the modifications we’ve made, it’s as simple as passing an array to the basemap() function.

Bringing it all together

You can Fiddle around with a working compound basemap selector below.

Why would you do such a thing?

Sometimes a basemap with just one tile layer just won’t cut it.

Other posts in this series

No comments:

Post a Comment