summaryrefslogtreecommitdiff
path: root/platform/darwin/docs/guides/Migrating to Expressions.md.ejs
blob: addbf6940ea2f6527f714a690e093b98149cbf97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
<%
  const os = locals.os;
  const iOS = os === 'iOS';
  const macOS = os === 'macOS';
  const cocoaPrefix = iOS ? 'UI' : 'NS';
  const guide = 'MigratingToExpressions';
-%>
<!--
  This file is generated.
  Edit platform/darwin/scripts/generate-style-code.js, then run `make darwin-style-code`.
-->

# Migrating from Style Functions to Expressions

[Runtime Styling](runtime-styling.html) enables you to modify every aspect of the map’s appearance dynamically as a user interacts with your application. Developers can specify in advance how a layout or paint attribute will vary as the zoom level changes or how the appearance of individual features vary based on metadata provided by a content source.

With Mapbox Maps SDK for <%- iOS ? 'iOS v4.0.0' : 'macOS v0.7.0' %>, style functions have been replaced with expressions. These provide even more tools for developers who want to style their maps dynamically. This guide outlines some tips for migrating from style functions to expressions, and offers an overview of some things that developers can do with expressions.

An expression is represented at runtime by the `NSExpression` class. Expressions can be used to style paint and layout properties based on zoom level, data attributes, or a combination of the two.

A constant expression can also be assigned to a style property. For example, the opacity of a fill style layer can be set to a constant value between 0 and 1.

The documentation for each individual style layer property notes which non-constant expressions are enabled for that property. Style functions supported four interpolation modes: exponential, interval, categorical, and identity.

This guide uses earthquake data from the [U.S. Geological Survey](https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php). Under each interpolation mode, the style function implementation will be shown, followed by the current syntax.

For more information about how to work with GeoJSON data in our <%- os %> SDK, please see our [working with GeoJSON data](working-with-geojson-data.html) guide. To learn more about supported expressions, see our ["Predicates and Expressions"](predicates-and-expressions.html) guide. The "Predicates and Expressions" guide also outlines Mapbox custom functions that can be used to dynamically style a map.

## Stops
Stops are dictionary keys that are associated with layer attribute values. Constant values no longer need to be wrapped as style values when they are values in a stops dictionary.


Style function syntax:

```swift
let stops = [
    0: MGLStyleValue<UIColor>(rawValue: .yellow),
    2.5: MGLStyleValue(rawValue: .orange),
    5: MGLStyleValue(rawValue: .red),
    7.5: MGLStyleValue(rawValue: .blue),
    10: MGLStyleValue(rawValue: .white),
]
```

Current syntax:
<%- guideExample(guide, 'Stops', os) %>


## Interpolation mode

Style functions supported four interpolation modes: exponential/linear, interval, categorical, and identity. For more information about supported custom expressions, please see the "Predicates and Expressions" guide.

### Linear

`+[NSExpression(MGLAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` takes the interpolation type as a parameter. If you previously used the default interpolation base, use the curve type `MGLExpressionInterpolationMode.linear`. See the [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code) documentation for more details.

The stops dictionary below, shows colors that continuously shift from yellow to orange to red to blue to white based on the attribute value.

Style function syntax:

```swift
let url = URL(string: "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson")!
let symbolSource = MGLSource(identifier: "source")
let symbolLayer = MGLSymbolStyleLayer(identifier: "place-city-sm", source: symbolSource)

let source = MGLShapeSource(identifier: "earthquakes", url: url, options: nil)
mapView.style?.addSource(source)

let stops = [
    0: MGLStyleValue<UIColor>(rawValue: .yellow),
    2.5: MGLStyleValue(rawValue: .orange),
    5: MGLStyleValue(rawValue: .red),
    7.5: MGLStyleValue(rawValue: .blue),
    10: MGLStyleValue(rawValue: .white),
]

let layer = MGLCircleStyleLayer(identifier: "circles", source: source)
layer.circleColor = MGLStyleValue(interpolationMode: .exponential,
                                  sourceStops: stops,
                                  attributeName: "mag",
                                  options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .green)])
layer.circleRadius = MGLStyleValue(rawValue: 10)
mapView.style?.insertLayer(layer, below: symbolLayer)
```

Current syntax:

<%- guideExample(guide, 'Linear', os) %>

### Exponential

If you previously used an interpolation base greater than `0` (other than `1`), you can use `MGLExpressionInterpolationMode.exponential` as the curve type for `+[NSExpression(MGLAdditions) mgl_expressionForInterpolatingExpression:withCurveType:parameters:stops:]` or `'exponential'` as the curve type for [`mgl_interpolate:withCurveType:parameters:stops:`](predicates-and-expressions.html#code-mgl_interpolate-withcurvetype-parameters-stops-code). The `parameters` argument takes that interpolation base. This interpolates between values exponentially, creating an accelerated ramp effect.

Here’s a visualization from Mapbox Studio (see [Working with Mapbox Studio](working-with-mapbox-studio.html)) comparing interpolation base values of `1.5` and `0.5` based on zoom. In order to convert camera style functions, use `$zoomLevel` or `MGL_FUNCTION('zoomLevel')` as the attribute key.

<img src="img/data-driven-styling/exponential-function.png" height=344/>
<img src="img/data-driven-styling/exponential-function-1.png" height=344/>

The example below increases a layer’s `circleRadius` exponentially based on a map’s zoom level. The interpolation base is `1.5`.

Style function syntax:

```swift
let stops = [
    12: MGLStyleValue<NSNumber>(rawValue: 0.5),
    14: MGLStyleValue(rawValue: 2),
    18: MGLStyleValue(rawValue: 18),
]

layer.circleRadius = MGLStyleValue(interpolationMode: .exponential,
                                   cameraStops: stops,
                                   options: [.interpolationBase: 1.5])
```

Current syntax:

<%- guideExample(guide, 'Exponential', os) %>

### Interval

Steps, or intervals, create a range using the keys from the stops dictionary. The range is from the given key to just less than the next key. The attribute values that fall into that range are then styled using the layout or paint value assigned to that key. You can use the `+[NSExpression(MGLAdditions) mgl_expressionForSteppingExpression:fromExpression:stops:]` method or the custom function [`mgl_step:from:stops:`](predicates-and-expressions.html#code-mgl_step-from-stops-code) for cases where you previously used interval interpolation mode. The first parameter takes the feature attribute name and the second parameter (`from:`) optionally takes the default or fallback value for that function. The final parameter takes a stops dictionary as an argument.

When we use the stops dictionary given above with an `'mgl_step:from:stops:'`, we create ranges where earthquakes with a magnitude of 0 to just less than 2.5 would be yellow, 2.5 to just less than 5 would be orange, and so on.

Style function syntax:

```swift
let stops = [
    0: MGLStyleValue<UIColor>(rawValue: .yellow),
    2.5: MGLStyleValue(rawValue: .orange),
    5: MGLStyleValue(rawValue: .red),
    7.5: MGLStyleValue(rawValue: .blue),
    10: MGLStyleValue(rawValue: .white),
]

layer.circleColor = MGLStyleValue(interpolationMode: .interval,
                                  sourceStops: stops,
                                  attributeName: "mag",
                                  options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .green)])
````

Current syntax:

<%- guideExample(guide, 'Interval', os) %>

### Categorical

Categorical interpolation mode took a stops dictionary. If the value for a specified feature attribute name matched one in that stops dictionary, the style value for that attribute value would be used. Categorical style functions can now be replaced with `MGL_MATCH`.

`MGL_MATCH` takes an initial condition, which in this case is an attribute key. This is followed by possible matches for that key and the value to assign to the layer property if there is a match. The final argument can be a default style value that is to be used if none of the specified values match.

There are three main types of events in the USGS dataset: earthquakes, explosions, and quarry blasts. In this case, the color of the circle layer will be determined by the type of event, with a default value of blue to catch any events that do not fall into any of those categories.

Style function syntax:

```swift
let categoricalStops = [
    "earthquake": MGLStyleValue<UIColor>(rawValue: .orange),
    "explosion": MGLStyleValue(rawValue: .red),
    "quarry blast": MGLStyleValue(rawValue: .yellow),
]

layer.circleColor = MGLStyleValue(interpolationMode: .categorical,
                                  sourceStops: categoricalStops,
                                  attributeName: "type",
                                  options: [.defaultValue: MGLStyleValue<UIColor>(rawValue: .blue)])
```

Current syntax:
<%- guideExample(guide, 'Categorical', os) %>

If your use case does not require a default value, you can either apply a predicate to your layer prior to styling it, or use the format string `"valueForKeyPath:"`.

### Identity

Identity interpolation mode used the attribute’s value as the style layer property value. In this example, you might set the `circleRadius` to the earthquake’s magnitude. In order to use a feature attribute value to style a layer property, set the property value to `[NSExpression expressionForKeyPath:]`, which take the feature attribute name as an argument.

Style function syntax:

```swift
layer.circleRadius = MGLStyleValue(interpolationMode: .identity,
                                   sourceStops: nil,
                                   attributeName: "mag",
                                   options: [.defaultValue: MGLStyleValue<NSNumber>(rawValue: 0)])
```

Current syntax:
<%- guideExample(guide, 'Identity', os) %>

![identity mode](img/data-driven-styling/identity.png)

Some built-in functions can be applied to attribute values to style layer property values. To set the circle radius to three times the earthquake’s magnitude, create a `multiply:by:` function that takes the attribute value and the multiplier as arguments, or use a format string.

<%- guideExample(guide, 'Multiply', os) %>

![multiply magnitude](img/data-driven-styling/multiply.png)

You can also cast attribute values in order to use them. One example is to cast an integer as an `NSString` and use it as a text value.

<%- guideExample(guide, 'Cast', os) %>

![cast a value](img/data-driven-styling/cast.png)

### Constant Values

For constant values that do not necessarily change based on camera or attribute values, use `[NSExpression expressionForConstantValue:]` (previously `[MGLStyleValue valueWithRawValue:]`).

## Resources

* [USGS Earthquake Feed](https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php)
* [For Style Authors](for-style-authors.html)
* [Predicates and Expressions](predicates-and-expressions.html)