首页 > 解决方案 > 想要在传单地图中添加 10 种不同类型的图标

问题描述

看看我的 R 代码,在这里我可以标记两种不同类型的标记图标,但我想用 10 种不同类型的标记图标标记 quakes$mag 列的所有 10 个值。

 quakes1 <- quakes[1:10,]

leafIcons <- icons(
  iconUrl = ifelse(quakes1$mag < 4.6,
                   "http://leafletjs.com/examples/custom-icons/leaf-green.png",
                   "http://leafletjs.com/examples/custom-icons/leaf-red.png"
  ),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62
)

leaflet(data = quakes1) %>% addTiles() %>%
  addMarkers(~long, ~lat, icon = leafIcons)

我尝试使用 switch 语句而不是 ifelse 来执行此操作,但它不适用于 switch。

标签: rdictionaryleafleticonsmarkers

解决方案


ifelse是一个矢量化的函数,它创建了你的图标矢量leafIcons。有多种方法可以矢量化或基于矢量switch创建您的替代方法- 请参阅此相关问题。您可以使用which可能是您正在寻找的:leafIconsdplyrcase_when

library(dplyr)
library(leaflet)

leafIcons <- icons(
  iconUrl = case_when(
    quakes1$mag <= 4.3 ~ "http://leafletjs.com/examples/custom-icons/leaf-green.png",
    4.3 < quakes1$mag & quakes1$mag <= 5 ~ "http://leafletjs.com/examples/custom-icons/leaf-orange.png",
    quakes1$mag > 5 ~ "http://leafletjs.com/examples/custom-icons/leaf-red.png"
  ),
  iconWidth = 38, iconHeight = 95,
  iconAnchorX = 22, iconAnchorY = 94,
  shadowUrl = "http://leafletjs.com/examples/custom-icons/leaf-shadow.png",
  shadowWidth = 50, shadowHeight = 64,
  shadowAnchorX = 4, shadowAnchorY = 62
)

如果您有一个数字向量,您也可以使用cut或者findInterval如果您想将图标分配给不同的范围。


推荐阅读