I would like to know if it is possible to add condition in the makeIcon() function
I have a table:
id ; lat ; long ; class1 ; class2 ; class3
And I want the icon to be different depending on these conditions:
if class1 == A, I want image1
else, if class2 == B, I want image2
else, if class3 == C, I want image 3
else, I want image4
Within makeIcon()
, probably not. From the API documentation:
For the simple case of applying a single icon to a set of markers, use makeIcon(). (link)
You probably want to use icon() which is a vector of icons that you can use to draw different icons for different data:
If you have several icons to apply that vary only by a couple of parameters (i.e. they share the same size and anchor points but have different URLs), use the icons() function.
Icons contains a vector with each icon image url (or any other icon property that differs among the data).
To do the logic, it might be easiest to nest an extra two ifelse statements into the icon function, something like:
iconUrl = ifelse(df$class1 == "a", "image1",
ifelse(df$class2 == "c", "image2",
ifelse(df$class3 =="x", "image3",
"some other url" #the else condition
)
)
),
Here's a minimal example that's just a slight addition to the example in the linked to api documentation:
library(leaflet)
lat<- c(57,65,60,61)
long<-c(-130,-125,-140,-135)
class1<-c("a","b","c","d")
class2<-c("b","c","d","e")
class3<-c("b","c","d","f")
df <- data.frame(lat,long,class1,class2,class3,stringsAsFactors=FALSE)
leafIcons <- icons(
iconUrl = ifelse(df$class1 == "a", "http://leafletjs.com/examples/custom-icons/leaf-green.png",
ifelse(df$class2 == "c", "http://leafletjs.com/examples/custom-icons/leaf-red.png",
ifelse(df$class3 == "d", "http://leafletjs.com/examples/custom-icons/leaf-orange.png",
"http://leafletjs.com/docs/images/logo.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 = df) %>% addTiles() %>%
addMarkers(~long, ~lat, icon = leafIcons)
Sorry the image selection in this isn't fantastic. If you want to some other property vary depending on the data for each icon, icon size for example, you use the same process on iconWidth and/or iconHeight:
iconHeight = ifelse(df$class1 == "a", 100,
ifelse(df$class2 == "c", 200,
ifelse(df$class3 == "d", 300,
400
)
)
),