資料驅動樣式運算式 (Android SDK)

注意

Azure 地圖服務 Android SDK 淘汰

適用於 Android 的 Azure 地圖服務 原生 SDK 現在已被取代,將於 3/31/25 淘汰。 若要避免服務中斷,請透過 3/31/25 移轉至 Azure 地圖服務 Web SDK。 如需詳細資訊,請參閱 Azure 地圖服務 Android SDK 移轉指南

運算式可讓您將商務邏輯套用至樣式選項,以觀察資料來源中每個圖形中定義的屬性。 運算式可以篩選資料來源或圖層中的資料。 運算式可能包含條件式邏輯,例如 if 陳述式。 而且可以用來使用以下項目操作資料:字串運算子、邏輯運算子和數學運算子。

資料驅動樣式可減少實作樣式商務邏輯所需的程式碼數量。 搭配圖層使用時,會在個別執行緒的轉譯時間評估運算式。 相較於評估 UI 執行緒上的商務邏輯,這項功能可提供更高的效能。

Azure 地圖服務 Android SDK 支援與 Azure 地圖服務 Web SDK 幾乎相同的樣式運算式,因此資料驅動樣式運算式 (Web SDK) 中概述的所有相同概念,都可以傳遞到 Android 應用程式中。 Azure 地圖服務 Android SDK 中的所有樣式運算式都可在 com.microsoft.azure.maps.mapcontrol.options.Expression 命名空間下使用。 樣式運算式分成許多不同的類型。

運算式的類型 描述
布林運算式 布林運算式提供一組布林運算子運算式來評估布林比較。
色彩運算式 色彩運算式可讓您更輕鬆地建立及操作色彩值。
條件運算式 條件運算式提供類似 if 陳述式的邏輯作業。
資料運算式 提供特徵中屬性資料的存取權。
插補與步驟運算式 插補與步驟運算式可用於依插補曲線或步驟函式來計算值。
以 JSON 為基礎的運算式 可讓您輕鬆地重複使用針對具有 Android SDK 的 Web SDK 建立的樣式原始以 JSON 為基礎的運算式。
圖層特定運算式 僅適用於單一圖層的特殊運算式。
數學運算式 提供數學運算子,以在運算式架構內執行資料驅動計算。
字串運算子運算式 字串運算子運算式會在串連和轉換案例等字串上執行轉換作業。
類型運算式 類型運算式提供用於測試和轉換不同資料類型 (例如字串、數字和布林值) 的工具。
變數繫結運算式 變數繫結運算式會將計算的結果儲存在變數中,並在運算式的其他位置多次參考,而不需要重新計算預存值。
縮放運算式 擷取地圖在轉譯時間的目前縮放層級。

注意

運算式的語法在 JAVA 和 Kotlin 中大致相同。 如果您已將文件設定為 Kotlin,但是會看到適用於 JAVA 的程式碼區塊,則這兩種語言的程式碼都相同。

此區段中的所有範例會使用下列功能來示範這些運算式的不同使用方式。

{
    "type": "Feature",
    "geometry": {
        "type": "Point",
        "coordinates": [-122.13284, 47.63699]
    },
    "properties": {
        "id": 123,
        "entityType": "restaurant",
        "revenue": 12345,
        "subTitle": "Building 40", 
        "temperature": 64,
        "title": "Cafeteria", 
        "zoneColor": "purple",
        "abcArray": ["a", "b", "c"],
        "array2d": [["a", "b"], ["x", "y"]],
        "_style": {
            "fillColor": "red"
        }
    }
}

下列程式碼示範如何在應用程式中手動建立此 GeoJSON 功能。

//Create a point feature.
Feature feature = Feature.fromGeometry(Point.fromLngLat(-100, 45));

//Add properties to the feature.
feature.addNumberProperty("id", 123);
feature.addStringProperty("entityType", "restaurant");
feature.addNumberProperty("revenue", 12345);
feature.addStringProperty("subTitle", "Building 40");
feature.addNumberProperty("temperature", 64);
feature.addStringProperty("title", "Cafeteria");
feature.addStringProperty("zoneColor", "purple");

JsonArray abcArray = new JsonArray();
abcArray.add("a");
abcArray.add("b");
abcArray.add("c");

feature.addProperty("abcArray", abcArray);

JsonArray array1 = new JsonArray();
array1.add("a");
array1.add("b");

JsonArray array2 = new JsonArray();
array1.add("x");
array1.add("y");

JsonArray array2d = new JsonArray();
array2d.add(array1);
array2d.add(array2);

feature.addProperty("array2d", array2d);

JsonObject style = new JsonObject();
style.addProperty("fillColor", "red");

feature.addProperty("_style", style);
//Create a point feature.
val feature = Feature.fromGeometry(Point.fromLngLat(-100, 45))

//Add properties to the feature.
feature.addNumberProperty("id", 123)
feature.addStringProperty("entityType", "restaurant")
feature.addNumberProperty("revenue", 12345)
feature.addStringProperty("subTitle", "Building 40")
feature.addNumberProperty("temperature", 64)
feature.addStringProperty("title", "Cafeteria")
feature.addStringProperty("zoneColor", "purple")

val abcArray = JsonArray()
abcArray.add("a")
abcArray.add("b")
abcArray.add("c")

feature.addProperty("abcArray", abcArray)

val array1 = JsonArray()
array1.add("a")
array1.add("b")

val array2 = JsonArray()
array1.add("x")
array1.add("y")

val array2d = JsonArray()
array2d.add(array1)
array2d.add(array2)

feature.addProperty("array2d", array2d)

val style = JsonObject()
style.addProperty("fillColor", "red")

feature.addProperty("_style", style)

下列程式碼示範如何將 JSON 物件的字串化版本還原序列化為應用程式中的 GeoJSON 功能。

String featureString = "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[-122.13284,47.63699]},\"properties\":{\"id\":123,\"entityType\":\"restaurant\",\"revenue\":12345,\"subTitle\":\"Building 40\",\"temperature\":64,\"title\":\"Cafeteria\",\"zoneColor\":\"purple\",\"abcArray\":[\"a\",\"b\",\"c\"],\"array2d\":[[\"a\",\"b\"],[\"x\",\"y\"]],\"_style\":{\"fillColor\":\"red\"}}}";

Feature feature = Feature.fromJson(featureString);
val featureString = "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[-122.13284,47.63699]},\"properties\":{\"id\":123,\"entityType\":\"restaurant\",\"revenue\":12345,\"subTitle\":\"Building 40\",\"temperature\":64,\"title\":\"Cafeteria\",\"zoneColor\":\"purple\",\"abcArray\":[\"a\",\"b\",\"c\"],\"array2d\":[[\"a\",\"b\"],[\"x\",\"y\"]],\"_style\":{\"fillColor\":\"red\"}}}"

val feature = Feature.fromJson(featureString)

以 JSON 為基礎的運算式

Azure 地圖服務 Web SDK 也支援使用 JSON 陣列代表的資料驅動樣式運算式。 這些相同運算式可以使用 Android SDK 中的原生 Expression 類別來重新建立。 或者,這些以 JSON 為基礎的運算式可以使用 Web 函式轉換成字串,例如 JSON.stringify,並傳遞至 Expression.raw(String rawExpression) 方法。 例如,採用下列 JSON 運算式。

var exp = ['get','title'];
JSON.stringify(exp); // = "['get','title']"

上述運算式的字串化版本會是 "['get','title']",而且可以讀取至如下所示的 Android SDK。

Expression exp = Expression.raw("['get','title']")
val exp = Expression.raw("['get','title']")

使用此方法可讓您輕鬆地在使用 Azure 地圖服務的行動裝置應用程式與 Web 應用程式之間重複使用樣式運算式。

此影片提供 Azure 地圖服務中資料驅動樣式的概觀。


資料運算式

資料運算式提供特徵中屬性資料的存取權。

運算式 傳回類型 描述
accumulated() 數值 取得到目前為止累積的叢集屬性值。 這只能用於叢集 DataSource 來源的 clusterProperties 選項。
at(number | Expression, Expression) value 從陣列擷取項目。
geometryType() string 取得特徵的幾何類型:Point、MultiPoint、LineString、MultiLineString、Polygon、MultiPolygon。
get(string | Expression) | get(string | Expression, Expression) value 從所提供物件的屬性取得屬性值。 如果遺漏要求的屬性,則傳回 Null。
has(string | Expression) | has(string | Expression, Expression) boolean 判斷特徵的屬性是否具有指定的屬性。
id() value 如果特徵具有識別碼,則取得該特徵的識別碼。
in(string | number | Expression, Expression) boolean 判斷項目是否存在於陣列中
length(string | Expression) 數值 取得字串或陣列的長度。
properties() value 取得特徵屬性物件。

Android SDK 不支援下列 Web SDK 樣式運算式:

  • index-of
  • slice

範例

您可以使用 get 運算式,直接在運算式中存取特徵的屬性。 這個範例會使用特徵的 zoneColor 值來指定泡泡圖層的色彩屬性。

BubbleLayer layer = new BubbleLayer(source,
    //Get the zoneColor value.
    bubbleColor(get("zoneColor"))
);
val layer = BubbleLayer(source,
    //Get the zoneColor value.
    bubbleColor(get("zoneColor"))
)

如果所有點特徵都有 zoneColor 屬性,則上述範例會正常運作。 如果沒有,色彩可能會回復為「黑色」。 若要修改後援色彩,請使用 switchCase 運算式搭配 has 運算式來檢查屬性是否存在。 如果屬性不存在,則傳回後援色彩。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        //Use a conditional case expression.
        switchCase(
            //Check to see if feature has a "zoneColor" 
            has("zoneColor"), 

            //If it does, use it.
            get("zoneColor"), 

            //If it doesn't, default to blue.
            literal("blue")
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        //Use a conditional case expression.
        switchCase(
            //Check to see if feature has a "zoneColor" 
            has("zoneColor"), 

            //If it does, use it.
            get("zoneColor"), 

            //If it doesn't, default to blue.
            literal("blue")
        )
    )
)

根據預設,泡泡與符號圖層會呈現資料來源中所有圖形的座標。 此行為可以醒目提示多邊形或線條的頂點。 圖層的 filter 選項可用於使用布林運算式中的 geometryType 運算式,來限制其所呈現特徵的幾何類型。 下列範例會限制泡泡圖層,以便只呈現 Point 功能。

BubbleLayer layer = new BubbleLayer(source,
    filter(eq(geometryType(), "Point"))
);
val layer = BubbleLayer(source,
    filter(eq(geometryType(), "Point"))
)

下列範例允許呈現 PointMultiPoint 功能。

BubbleLayer layer = new BubbleLayer(source,
    filter(any(eq(geometryType(), "Point"), eq(geometryType(), "MultiPoint")))
);
val layer = BubbleLayer(source,
    filter(any(eq(geometryType(), "Point"), eq(geometryType(), "MultiPoint")))
)

同樣地,多邊形的外框會在線條圖層中呈現。 若要在線條圖層中停用此行為,請新增只允許 LineStringMultiLineString 特徵的篩選。

以下是如何使用資料運算式的其他範例:

//Get item [2] from an array "properties.abcArray[1]" = "c"
at(2, get("abcArray"))

//Get item [0][1] from a 2D array "properties.array2d[0][1]" = "b"
at(1, at(0, get("array2d")))

//Check to see if a value is in an array "properties.abcArray.indexOf('a') !== -1" = true
in("a", get("abcArray"))

//Get the length of an array "properties.abcArray.length" = 3
length(get("abcArray"))

//Get the value of a subproperty "properties._style.fillColor" = "red"
get("fillColor", get("_style"))

//Check that "fillColor" exists as a subproperty of "_style".
has("fillColor", get("_style"))

數學運算式

數學運算式提供數學運算子,以在運算式架構內執行資料驅動計算。

運算式 傳回類型 描述
abs(number | Expression) 數值 計算指定數值的絕對值。
acos(number | Expression) 數值 計算指定數字的反餘弦函數。
asin(number | Expression) 數值 計算指定數字的反正弦函數。
atan(number | Expression) 數值 計算指定數字的反正切函數。
ceil(number | Expression) 數值 將數字四捨五入到下一個整數。
cos(number | Expression) 數值 計算指定數字的 cos 函數。
division(number, number) | division(Expression, Expression) 數值 將第一個數字除以第二個數字。 Web SDK 對等運算式:/
e() 數值 傳回數學常數 e
floor(number | Expression) 數值 將數字四捨五入到上一個整數。
log10(number | Expression) 數值 計算指定數字的以十為底的對數。
log2(number | Expression) 數值 計算指定數字的以二為底的對數。
ln(number | Expression) 數值 計算指定數字的自然對數。
ln2() 數值 傳回數學常數 ln(2)
max(numbers... | expressions...) 數值 計算指定數字集的最大數字。
min(numbers... | expressions...) 數值 計算指定數字集的最小數字。
mod(number, number) | mod(Expression, Expression) 數值 計算第一個數字除以第二個數字時的餘數。 Web SDK 對等運算式:%
pi() 數值 傳回數學常數 PI
pow(number, number) | pow(Expression, Expression) 數值 計算第一個值乘至第二個數字乘冪的值。
product(numbers... | expressions...) 數值 將指定的數字相乘。 Web SDK 對等運算式:*
round(number | Expression) 數值 將數字四捨五入為最接近的整數。 中間值從零四捨五入。 例如,round(-1.5) 評估為 -2
sin(number | Expression) 數值 計算指定數字的正弦函數。
sqrt(number | Expression) 數值 計算指定數字的平方根。
subtract(number | Expression 數值 將 0 減去指定的數字。
subtract(number | Expression, number | Expression) 數值 將第一個數字減去第二個數字。
sum(numbers... | expressions...) 數值 計算指定數字的總和。
tan(number | Expression) 數值 計算指定數字的正切函數。

布林運算式

布林運算式提供一組布林運算子運算式來評估布林比較。

比較值時,會嚴格輸入比較。 不同類型的值一律視為不相等。 在剖析時間已知不同型別的案例會被視為無效,並且會產生剖析錯誤。

運算式 傳回類型 描述
all(Expression...) boolean 如果所有輸入是 true 則傳回 true,否則傳回 false
any(Expression...) boolean 如果任何輸入是 true 則傳回 true,否則傳回 false
eq(Expression compareOne, Expression | boolean | number | string compareTwo) | eq(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果輸入值相等則傳回 true,否則傳回 false。 引數必須是兩個字串或兩個數字。
gt(Expression compareOne, Expression | boolean | number | string compareTwo) | gt(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果第一個輸入大於第二個輸入,則傳回 true,否則傳回 false。 引數必須是兩個字串或兩個數字。
gte(Expression compareOne, Expression | boolean | number | string compareTwo) | gte(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果第一個輸入大於或等於第二個輸入,則傳回 true,否則傳回 false。 引數必須是兩個字串或兩個數字。
lt(Expression compareOne, Expression | boolean | number | string compareTwo) | lt(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果第一個輸入小於第二個輸入,則傳回 true,否則傳回 false。 引數必須是兩個字串或兩個數字。
lte(Expression compareOne, Expression | boolean | number | string compareTwo) | lte(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果第一個輸入小於或等於第二個輸入,則傳回 true,否則傳回 false。 引數必須是兩個字串或兩個數字。
neq(Expression compareOne, Expression | boolean | number | string compareTwo) | neq(Expression compareOne, Expression | string compareTwo, Expression collator) boolean 如果輸入值不相等則傳回 true,否則傳回 false
not(Expression | boolean) boolean 邏輯否定。 如果輸入是 false 則傳回 true,如果輸入是 true 則傳回 false

條件運算式

條件運算式提供類似 if 陳述式的邏輯作業。

下列運算式會對輸入資料執行條件式邏輯作業。 例如,switchCase 運算式會提供「if/then/else」邏輯,而 match 運算式則像是「switch-statement」。

切換大小寫運算式

switchCase 運算式是一種條件運算式,提供「if/then/else」邏輯。 這種類型的運算式會逐步執行布林條件清單。 會傳回第一個布林條件的輸出值,以評估為 true。

下列虛擬程式碼會定義 switchCase 運算式的結構。

switchCase(
    condition1: boolean expression, 
    output1: value,
    condition2: boolean expression, 
    output2: value,
    ...,
    fallback: value
)

範例

下列範例會逐步執行不同的布林值條件,直到找到評估為 true 的布林值,然後傳回相關聯的值。 如果沒有布林條件評估為 true,則會傳回後援值。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        switchCase(
            //Check to see if the first boolean expression is true, and if it is, return its assigned result.
            //If it has a zoneColor property, use its value as a color.
            has("zoneColor"), toColor(get("zoneColor")),

            //Check to see if the second boolean expression is true, and if it is, return its assigned result.
            //If it has a temperature property with a value greater than or equal to 100, make it red.
            all(has("temperature"), gte(get("temperature"), 100)), color(Color.RED),

            //Specify a default value to return. In this case green.
            color(Color.GREEN)
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        switchCase(
            //Check to see if the first boolean expression is true, and if it is, return its assigned result.
            //If it has a zoneColor property, use its value as a color.
            has("zoneColor"), toColor(get("zoneColor")),

            //Check to see if the second boolean expression is true, and if it is, return its assigned result.
            //If it has a temperature property with a value greater than or equal to 100, make it red.
            all(has("temperature"), gte(get("temperature"), 100)), color(Color.RED),

            //Specify a default value to return. In this case green.
            color(Color.GREEN)
        )
    )
)

比對運算式

match 運算式是一種條件運算式,可提供 switch 陳述式樣式的邏輯。 輸入可以是任何運算式 (例如 get( "entityType")),可傳回字串或數字。 每個停止都必須有一個標籤,也就是單一常值或常值陣列,其值必須是所有字串或所有數字。 如果陣列中的任何值相符,輸入就會相符。 每個停止標籤都必須是唯一的。 如果輸入類型與標籤類型不相符,結果會是預設後援值。

下列虛擬程式碼會定義 match 運算式的結構。

match(Expression input, Expression defaultOutput, Expression.Stop... stops)

範例

下列範例會查看泡泡圖層中點特徵的 entityType 屬性,並搜尋相符項目。 若找到相符項目,則會傳回指定的值,或傳回後援值。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        match(
            //Get the input value to match.
            get("entityType"),

            //Specify a default value to return if no match is found.
            color(Color.BLACK),

            //List the values to match and the result to return for each match.

            //If value is "restaurant" return "red".
            stop("restaurant", color(Color.RED)),

            //If value is "park" return "green".
            stop("park", color(Color.GREEN))
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        match(
            //Get the input value to match.
            get("entityType"),

            //Specify a default value to return if no match is found.
            color(Color.BLACK),

            //List the values to match and the result to return for each match.

            //If value is "restaurant" return "red".
            stop("restaurant", color(Color.RED)),

            //If value is "park" return "green".
            stop("park", color(Color.GREEN))
        )
    )
)

下列範例會使用陣列來列出一組應該傳回相同值的標籤。 此方法比個別列出每個標籤更有效率。 在此情況下,如果 entityType 屬性是「restaurant」或「grocery_store」,則會傳回色彩「red」。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        match(
            //Get the input value to match.
            get("entityType"),

            //Specify a default value to return if no match is found.
            color(Color.BLACK),

            //List the values to match and the result to return for each match.

            //If value is "restaurant" or "grocery_store" return "red".
            stop(Arrays.asList("restaurant", "grocery_store"), color(Color.RED)),

            //If value is "park" return "green".
            stop("park", color(Color.GREEN))
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        match(
            //Get the input value to match.
            get("entityType"),

            //Specify a default value to return if no match is found.
            color(Color.BLACK),

            //List the values to match and the result to return for each match.

            //If value is "restaurant" or "grocery_store" return "red".
            stop(arrayOf("restaurant", "grocery_store"), color(Color.RED)),

            //If value is "park" return "green".
            stop("park", color(Color.GREEN))
        )
    )
)

COALESCE 運算式

coalesce 運算式會逐步執行一組運算式,直到取得第一個非 Null 值並傳回該值為止。

下列虛擬程式碼會定義 coalesce 運算式的結構。

coalesce(Expression... input)

範例

下列範例會使用 coalesce 運算式來設定符號圖層的 textField 選項。 若 title 屬性從功能中遺漏或設定為 null,則運算式會嘗試尋找 subTitle 屬性,若該屬性遺漏或 null,則會回復為空字串。

SymbolLayer layer = new SymbolLayer(source,
    textField(
        coalesce(
            //Try getting the title property.
            get("title"),

            //If there is no title, try getting the subTitle. 
            get("subTitle"),

            //Default to an empty string.
            literal("")
        )
    )
);
val layer = SymbolLayer(source,
    textField(
        coalesce(
            //Try getting the title property.
            get("title"),

            //If there is no title, try getting the subTitle. 
            get("subTitle"),

            //Default to an empty string.
            literal("")
        )
    )
)

類型表示方式

類型運算式提供用於測試和轉換不同資料類型 (例如字串、數字和布林值) 的工具。

運算式 傳回類型 描述
array(Expression) Object[] 判斷提示輸入為陣列。
bool(Expression) boolean 判斷提示輸入值是布林值。
collator(boolean caseSensitive, boolean diacriticSensitive) | collator(boolean caseSensitive, boolean diacriticSensitive, java.util.Locale locale) | collator(Expression caseSensitive, Expression diacriticSensitive) | collator(Expression caseSensitive, Expression diacriticSensitive, Expression locale) 定序器 傳回定序器,以用於地區設定相依的比較作業。 區分大小寫和區分變音符號的選項預設為 false。 地區設定引數會指定要使用之地區設定的 IETF 語言標記。 如果未提供任何地區設定,則會使用預設地區設定。 如果要求的地區設定無法使用,則定序器會使用系統定義的後援地區設定。 使用 resolved-locale 來測試地區設定後援行為的結果。
literal(boolean \| number \| string \| Object \| Object[]) 布林值 | 數字 | 字串 | 物件 | Object[] 傳回常值陣列或物件值。 使用此運算式可防止陣列或物件評估為運算式。 當運算式需要傳回陣列或物件時,這是必要的。
number(Expression) 數值 判斷提示輸入值是數字。
object(Expression) Object 判斷提示輸入值是物件。
string(Expression) string 判斷提示輸入值是字串。
toArray(Expression) Object[] 將運算式轉換為 JSON 物件陣列。
toBool(Expression) boolean 將輸入值轉換為布林值。
toNumber(Expression) 數值 盡可能將輸入值轉換為數字。
toString(Expression) string 將輸入值轉換為字串。
typeoOf(Expression) string 傳回字串,描述指定值的類型。

色彩運算式

色彩運算式可讓您更輕鬆地建立及操作色彩值。

運算式 傳回類型 描述
color(int) color 將色彩整數值轉換成色彩運算式。
rgb(Expression red, Expression green, Expression blue) | rgb(number red, number green, number blue) color 紅色綠色藍色元件建立色彩值,範圍必須介於 0255 之間,以及 Alpha 元件 1。 如果有任何元件超出範圍,運算式就會是錯誤的。
rgba(Expression red, Expression green, Expression blue, Expression alpha) | rgba(number red, number green, number blue, number alpha) color 紅色綠色藍色元件建立色彩值,範圍必須介於 0255 之間,以及範圍在 01 之間的 Alpha 元件。 如果有任何元件超出範圍,運算式就會是錯誤的。
toColor(Expression) color 將輸入值轉換為色彩。
toRgba(Expression) color 傳回四個元素陣列,(依序) 包含輸入色彩紅色、綠色、藍色和 Alpha 元件。

範例

下列範例會建立 RGB 色彩值,紅色的值為 255綠色藍色的值是依據將 2.5 乘以 temperature 屬性的值來計算。 溫度變更時,色彩會變更為不同的紅色陰影。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        //Create a RGB color value.
        rgb(
            //Set red value to 255. Wrap with literal expression since using expressions for other values.
            literal(255f),    

            //Multiple the temperature by 2.5 and set the green value.
            product(literal(2.5f), get("temperature")), 

            //Multiple the temperature by 2.5 and set the blue value.
            product(literal(2.5f), get("temperature")) 
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        //Create a RGB color value.
        rgb(
            //Set red value to 255. Wrap with literal expression since using expressions for other values.
            literal(255f),    

            //Multiple the temperature by 2.5 and set the green value.
            product(literal(2.5f), get("temperature")), 

            //Multiple the temperature by 2.5 and set the blue value.
            product(literal(2.5f), get("temperature")) 
        )
    )
)

如果所有色彩參數都是數字,就不需要用 literal 運算式來包裝。 例如:

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        //Create a RGB color value.
        rgb(
            255f,  //Set red value to 255.

            150f,  //Set green value to 150.

            0f     //Set blue value to 0.
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        //Create a RGB color value.
        rgb(
            255f,  //Set red value to 255.

            150f,  //Set green value to 150.

            0f     //Set blue value to 0.
        )
    )
)

提示

字串色彩值可以使用 android.graphics.Color.parseColor 方法轉換為色彩。 以下會將十六進位色彩字串轉換成可與圖層搭配使用的色彩運算式。

color(parseColor("#ff00ff"))

字串運算子運算式

字串運算子運算式會在串連和轉換案例等字串上執行轉換作業。

運算式 傳回類型 描述
concat(string...) | concat(Expression...) string 將多個字串串連在一起。 每個值都必須是字串。 如有需要,請使用 toString 類型運算式,將其他實值型別轉換成字串。
downcase(string) | downcase(Expression) string 將指定字串轉換為小寫。
isSupportedScript(string) | isSupportedScript(Expression) boolean 判斷輸入字串是否使用目前字型堆疊所支援的字元集。 例如:isSupportedScript("ಗೌರವಾರ್ಥವಾಗಿ")
resolvedLocale(Expression collator) string 傳回所提供定序器使用之地區設定的 IETF 語言標記。 這可用來判斷預設系統地區設定,或判斷要求的地區設定是否已成功載入。
upcase(string) | upcase(Expression) string 將指定字串轉換為大寫。

範例

下列範例會將點特徵的 temperature 屬性轉換成字串,然後將 「°F」串連至其結尾。

SymbolLayer layer = new SymbolLayer(source,
    textField(
        concat(Expression.toString(get("temperature")), literal("°F"))
    ),

    //Some additional style options.
    textOffset(new Float[] { 0f, -1.5f }),
    textSize(12f),
    textColor("white")
);
val layer = SymbolLayer(source,
    textField(
        concat(Expression.toString(get("temperature")), literal("°F"))
    ),

    //Some additional style options.
    textOffset(new Float[] { 0f, -1.5f }),
    textSize(12f),
    textColor("white")
)

上述運算式會在地圖上呈現圖釘,並將文字「64°F」重疊在地圖上方,如下圖所示。

字串運算符表示式範例

插補與步驟運算式

插補與步驟運算式可用於依插補曲線或步驟函式來計算值。 這些運算式會採用傳回數值作為其輸入的運算式,例如 get("temperature")。 輸入值會根據輸入與輸出值的配對進行評估,以判斷最適合插補曲線或步驟函式的值。 輸出值稱為 "stops"。 每個停駐點的輸入值都必須是數字,並以遞增排序。 輸出值必須是數字、數字陣列或色彩。

插補運算式

interpolate 運算式可用於計算連續且順暢的值集合,方法是在停止值之間插補。 傳回色彩值的 interpolate 運算式會產生從中選取結果值的色彩漸層。 interpolate 運算式具有下列格式:

//Stops consist of two expressions.
interpolate(Expression.Interpolator interpolation, Expression number, Expression... stops)

//Stop expression wraps two values.
interpolate(Expression.Interpolator interpolation, Expression number, Expression.Stop... stops)

interpolate 運算式中可以使用三種類型的插補方法:

名稱 描述
linear() 在停住點配對之間,以線性方式插補。
exponential(number) | exponential(Expression) 在停駐點之間,以指數方式插補。 指定「基底」,並控制輸出增加的速率。 較高的值可讓輸出增加至範圍頂端。 接近 1 的「基底」值會產生更線性增加的輸出。
cubicBezier(number x1, number y1, number x2, number y2) | cubicBezier(Expression x1, Expression y1, Expression x2, Expression y2) 以指定控制點所定義的三次方貝茲曲線進行插補。

stop 運算式的格式為 stop(stop, value)

以下是這些不同型別的插補樣式範例。

線性 指數 三次方貝茲
線性插補圖 指數插補圖 立方貝塞爾插補圖

範例

下列範例會使用 linear interpolate 運算式,根據點特徵的 temperature 屬性來設定泡泡圖層的 bubbleColor 屬性。 若 temperature 值小於 60,則會傳回「藍色」。 如果值介於 60 到 70 之間 (不含 70),則會傳回黃色。 若該值介於 70 和 80 之間 (不含 80),則會傳回「橙色」(#FFA500)。 若該值為 80 或更大的值,則會傳回「紅色」。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        interpolate(
            linear(),
            get("temperature"),
            stop(50, color(Color.BLUE)),
            stop(60, color(Color.YELLOW)),
            stop(70, color(parseColor("#FFA500"))),
            stop(80, color(Color.RED))
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        interpolate(
            linear(),
            get("temperature"),
            stop(50, color(Color.BLUE)),
            stop(60, color(Color.YELLOW)),
            stop(70, color(parseColor("#FFA500"))),
            stop(80, color(Color.RED))
        )
    )
)

下圖示範如何為上述運算式選擇色彩。

插補表達式範例

步驟運算式

step 運算式可用於評估停駐點所定義的分段常數函式,以計算離散式及分層式結果值。

interpolate 運算式具有下列格式:

step(Expression input, Expression defaultOutput, Expression... stops)

step(Expression input, Expression defaultOutput, Expression.Stop... stops)

step(Expression input, number defaultOutput, Expression... stops)

step(Expression input, number defaultOutput, Expression.Stop... stops)

step(number input, Expression defaultOutput, Expression... stops)

step(number input, Expression defaultOutput, Expression.Stop... stops)

step(number input, number defaultOutput, Expression... stops)

step(number input, number defaultOutput, Expression.Stop... stops)

步驟運算式會在輸入值之前傳回停駐點的輸出值,若輸入小於第一個停駐點,則傳回第一個輸入值。

範例

下列範例會使用 step 運算式,根據點特徵的 temperature 屬性來設定泡泡圖層的 bubbleColor 屬性。 若 temperature 值小於 60,則會傳回「藍色」。 若值介於 60 到 70 之間 (不含 70),則會傳回「黃色」。 若該值介於 70 到 80 之間 (不含 80),則會傳回「橙色」。 若該值為 80 或更大的值,則會傳回「紅色」。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(
        step(
            get("temperature"),
            color(Color.BLUE),
            stop(60, color(Color.YELLOW)),
            stop(70, color(parseColor("#FFA500"))),
            stop(80, color(Color.RED))
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(
        step(
            get("temperature"),
            color(Color.BLUE),
            stop(60, color(Color.YELLOW)),
            stop(70, color(parseColor("#FFA500"))),
            stop(80, color(Color.RED))
        )
    )
)

下圖示範如何為上述運算式選擇色彩。

步驟表達式範例

圖層特定運算式

僅適用於特定圖層的特殊運算式。

熱度圖密度運算式

熱度圖密度運算式會擷取熱度圖圖層中每個像素的熱度圖密度值,並定義為 heatmapDensity。 這個值是介於 01 之間的數字。 其會與 interpolationstep 運算式搭配使用,以定義用於為熱度圖上色的色彩漸層。 此運算式只能在熱度圖層的 heatmapColor 選項中使用。

提示

插補運算式中位於索引 0 的色彩與分階色彩中的預設色彩,定義沒有資料之區域的色彩。 索引 0 的色彩可用於定義背景色彩。 許多人偏好將此值設定為透明或半透明的黑色。

範例

此範例會使用線性插補運算式來建立平滑色彩漸層,以呈現熱度圖。

HeatMapLayer layer = new HeatMapLayer(source,
    heatmapColor(
        interpolate(
            linear(),
            heatmapDensity(),
            stop(0, color(Color.TRANSPARENT)),
            stop(0.01, color(Color.MAGENTA)),
            stop(0.5, color(parseColor("#fb00fb"))),
            stop(1, color(parseColor("#00c3ff")))
        )
    )
);
val layer = HeatMapLayer(source,
    heatmapColor(
        interpolate(
            linear(),
            heatmapDensity(),
            stop(0, color(Color.TRANSPARENT)),
            stop(0.01, color(Color.MAGENTA)),
            stop(0.5, color(parseColor("#fb00fb"))),
            stop(1, color(parseColor("#00c3ff")))
        )
    )
)

除了使用平滑漸層將熱度圖上色之外,也可以使用 step 運算式,在一組範圍內指定色彩。 使用 step 運算式,將熱度圖以視覺化方式將密度分解成類似分佈或雷達圖樣式地圖的範圍。

HeatMapLayer layer = new HeatMapLayer(source,
    heatmapColor(
        step(
            heatmapDensity(),
            color(Color.TRANSPARENT),
            stop(0.01, color(parseColor("#000080"))),
            stop(0.25, color(parseColor("#000080"))),
            stop(0.5, color(Color.GREEN)),
            stop(0.5, color(Color.YELLOW)),
            stop(1, color(Color.RED))
        )
    )
);
val layer = HeatMapLayer(source,
    heatmapColor(
        step(
            heatmapDensity(),
            color(Color.TRANSPARENT),
            stop(0.01, color(parseColor("#000080"))),
            stop(0.25, color(parseColor("#000080"))),
            stop(0.5, color(Color.GREEN)),
            stop(0.5, color(Color.YELLOW)),
            stop(1, color(Color.RED))
        )
    )
)

如需詳細資訊,請參閱新增熱度圖層文件。

線條進度運算式

線條進度運算式會沿著線條圖層中的漸層線條擷取進度,並定義為 lineProgress()。 這個值是介於 0 和 1 之間的數字。 會與 interpolationstep 運算式搭配使用。 此運算式只能與線條圖層的 strokeGradient 選項搭配使用。

注意

線條圖層的 strokeGradient 選項需要將資料來源的 lineMetrics 選項設定為 true

範例

此範例會使用 lineProgress() 運算式,將色彩漸層套用至線條的筆觸。

LineLayer layer = new LineLayer(source,
    strokeGradient(
        interpolate(
            linear(),
            lineProgress(),
            stop(0, color(Color.BLUE)),
            stop(0.1, color(Color.argb(255, 65, 105, 225))), //Royal Blue
            stop(0.3, color(Color.CYAN)),
            stop(0.5, color(Color.argb(255,0, 255, 0))), //Lime
            stop(0.7, color(Color.YELLOW)),
            stop(1, color(Color.RED))
        )
    )
);
val layer = LineLayer(source,
    strokeGradient(
        interpolate(
            linear(),
            lineProgress(),
            stop(0, color(Color.BLUE)),
            stop(0.1, color(Color.argb(255, 65, 105, 225))), //Royal Blue
            stop(0.3, color(Color.CYAN)),
            stop(0.5, color(Color.argb(255,0, 255, 0))), //Lime
            stop(0.7, color(Color.YELLOW)),
            stop(1, color(Color.RED))
        )
    )
)

查看即時範例

文字欄位格式運算式

format 運算式可以搭配符號圖層的 textField 選項使用,以提供混合的文字格式設定。 此運算式會接受一或多個 formatEntry 運算式,以指定要附加至文字欄位的字串和 formatOptions 集合。

運算式 描述
format(Expression...) 傳回格式化文字,其中包含用於混合格式文字欄位項目的註釋。
formatEntry(Expression text) | formatEntry(Expression text, Expression.FormatOption... formatOptions) | formatEntry(String text) | formatEntry(String text, Expression.FormatOption... formatOptions) 傳回格式化字串項目,以用於 format 運算式。

可用的格式選項如下:

運算式 描述
formatFontScale(number) | formatFontScale(Expression) 指定字型大小的縮放係數。 如果已指定,則這個值將會覆寫個別字串中的 textSize 屬性。
formatTextFont(string[]) | formatTextFont(Expression) 指定要在轉譯時套用至文字的色彩。

範例

下列範例會新增粗體字型並擴大特徵 title 屬性的字型大小,來格式化文字欄位。 此範例也會在新行上新增特徵的 subTitle 屬性,並且縮小字型大小。

SymbolLayer layer = new SymbolLayer(source,
    textField(
        format(
            //Bold the title property and scale its font size up.
            formatEntry(
                get("title"),
                formatTextFont(new String[] { "StandardFont-Bold" }),
                formatFontScale(1.25)),

            //Add a new line without any formatting.
            formatEntry("\n"),

            //Scale the font size down of the subTitle property.
            formatEntry(
                get("subTitle"),
                formatFontScale(0.75))
        )
    )
);
val layer = SymbolLayer(source,
    textField(
        format(
            //Bold the title property and scale its font size up.
            formatEntry(
                get("title"),
                formatTextFont(arrayOf("StandardFont-Bold")),
                formatFontScale(1.25)),

            //Add a new line without any formatting.
            formatEntry("\n"),

            //Scale the font size down of the subTitle property.
            formatEntry(
                get("subTitle"),
                formatFontScale(0.75))
        )
    )
)

此圖層會轉譯點特徵,如下圖所示:

具有格式化文字欄位的點功能影像

縮放運算式

zoom 運算式是用來擷取呈現時地圖的目前縮放層級,並且定義為 zoom()。 此運算式會傳回地圖最小和最大縮放層級範圍之間的數字。 Web 和 Android 的 Azure 地圖服務互動式地圖控制項支援 25 個縮放層級,編號 0 到 24。 使用 zoom 運算式可隨著地圖的縮放層級變更,動態修改樣式。 zoom 運算式只能與 interpolatestep 運算式搭配使用。

範例

在所有縮放比例中,熱度圖層中呈現的資料點半徑預設有固定像素半徑。 縮放地圖時,資料會彙總在一起,且熱度圖層看起來會不一樣。 zoom 運算式可用於調整每個縮放層級的半徑,讓每個資料點都能涵蓋地圖的相同實體區域。 這會使熱度圖層看起來更靜態且一致。 地圖的每個縮放比例在垂直和水平方向的像素數目是前一縮放比例的兩倍。 如果將半徑調整為每一個縮放比例的兩倍,則建立的熱度圖在所有縮放比例上看起來都一致。 其可搭配使用 zoom 運算式與 base 2 exponential interpolation 運算式來完成,並針對最小縮放層級設定像素半徑,以及計算為如下所示之 2 * Math.pow(2, minZoom - maxZoom) 最大縮放層級的縮放半徑。

HeatMapLayer layer = new HeatMapLayer(source,
    heatmapRadius(
        interpolate(
            exponential(2),
            zoom(),

            //For zoom level 1 set the radius to 2 pixels.
            stop(1, 2),

            //Between zoom level 1 and 19, exponentially scale the radius from 2 pixels to 2 * (maxZoom - minZoom)^2 pixels.
            stop(19, 2 * Math.pow(2, 19 - 1))
        )
    )
);
val layer = HeatMapLayer(source,
    heatmapRadius(
        interpolate(
            exponential(2),
            zoom(),

            //For zoom level 1 set the radius to 2 pixels.
            stop(1, 2),

            //Between zoom level 1 and 19, exponentially scale the radius from 2 pixels to 2 * (maxZoom - minZoom)^2 pixels.
            stop(19, 2 * Math.pow(2, 19 - 1))
        )
    )
)

變數繫結運算式

變數繫結運算式會將計算的結果儲存在變數中。 因此,計算結果可以在運算式的其他位置多次參考。 對於牽涉到許多計算的運算式而言,這是非常實用的最佳化方式。

運算式 傳回類型 描述
let(Expression... input) 將一或多個值儲存為變數,以供傳回結果的子運算式中的 var 運算式使用。
var(Expression expression) | var(string variableName) Object 參考使用 let 運算式建立的變數。

範例

這個範例會使用運算式來計算相對於溫度比率的收益,然後使用 case 運算式來評估此值上的不同布林值運算。 let 運算式是用來儲存相對於溫度比率的收益,因此只需要計算一次。 var 運算式會視需要經常參考此變數,不需要重新計算。

BubbleLayer layer = new BubbleLayer(source,
    bubbleColor(           
        let(
            //Divide the point features `revenue` property by the `temperature` property and store it in a variable called `ratio`.
            literal("ratio"), division(get("revenue"), get("temperature")),

            //Evaluate the child expression in which the stored variable will be used.
            switchCase(
                //Check to see if the ratio is less than 100, return 'red'.
                lt(var("ratio"), 100), color(Color.RED),

                //Check to see if the ratio is less than 200, return 'green'.
                lt(var("ratio"), 200), color(Color.GREEN),

                //Return `blue` for values greater or equal to 200.
                color(Color.BLUE)
            )
        )
    )
);
val layer = BubbleLayer(source,
    bubbleColor(           
        let(
            //Divide the point features `revenue` property by the `temperature` property and store it in a variable called `ratio`.
            literal("ratio"), division(get("revenue"), get("temperature")),

            //Evaluate the child expression in which the stored variable will be used.
            switchCase(
                //Check to see if the ratio is less than 100, return 'red'.
                lt(var("ratio"), 100), color(Color.RED),

                //Check to see if the ratio is less than 200, return 'green'.
                lt(var("ratio"), 200), color(Color.GREEN),

                //Return `blue` for values greater or equal to 200.
                color(Color.BLUE)
            )
        )
    )
)

下一步

深入了解支援運算式的圖層: