I am working on a map with Leaflet in R. My data is stored as x,y coordinates, which are now transformed into lng, lat values.
Dataset: Dambrug2019 (my own dataset, just to avoid confusion in the next code sample).
Name Status x y
1 Point_1 0 482670 6217698
Transform:
Locations <- st_as_sf(Dambrug2019, coords=c("x", "y"))
%>% st_set_crs(23032) %>% st_transform(4326)
Name Status geometry
1 Point_1 1 POINT (8.720061 56.10223)
When making a map with the same markers for them all, everything works out well.
Map <- leaflet() %>% addTiles() %>% addMarkers(data=Locations, popup=Locations$Name)
Then I want to color the markers depending on the Status.
#Color the markers depending on the status.
#Want 0=green, 1=red, 2=orange.
> Color_status <- function(Locations) {sapply(Locations$Status,
function(Status) {if(Status==0){"green"} else if(Status==1)
{"red"} else{"orange"} })}
> Status_Icons <- awesomeIcons(icon='circle', iconColor=
'black', library='ion', markerColor=Color_status(Locations))
> leaflet(Locations) %>% addTiles() %>%
addAwesomeMarkers(c(Locations$geometry), icon=icons,
label=~as.character(Name))
Error in validateCoords(lng, lat, funcName) :
addAwesomeMarkers requires numeric longitude values
So, it seems like the addAwesomeMarkers cannot handle the way my points are set up. Is there in easy/quick way of turning the points into something the function can use?
Or do you know of an alternative way to create differently colored markers that would work with my current data?
Solution tried:
as.numeric(Locations$geometry)
Error: (list) object cannot be coerced to type 'double'
Result of print(Locations$gemometry):
> print(Locations$geometry)
Geometry set for 53 features
geometry type: POINT
dimension: XY
bbox: xmin: 8.269083 ymin: 54.89636 xmax: 15.13583 ymax: 56.99576
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
First 5 geometries:
POINT (8.720061 56.10223)
POINT (9.611723 56.67828)
POINT (8.633127 55.69979)
POINT (9.671523 56.99576)
POINT (15.13583 55.05837)
Thank you very much for your help in advance. :)
I'm not very familiar with the leaflet
and sf
packages, but give this a try:
library(st)
library(leaflet)
lng = as.numeric(st_coordinates(Locations$geometry)[,1])
lat = as.numeric(st_coordinates(Locations$geometry)[,2])
leaflet(Locations) %>% addTiles() %>%
addAwesomeMarkers(lng = lng, lat = lat, icon=icons,
label=~as.character(Name))