markers color based on data

I want to write a code to read data from an excel file and plot the points on a map.
I want the color of the marker to be determined based on the ship type.

library(leaflet)
library(readxl)

Read the Excel file

data <- read_excel("/Users/jevondixon/Downloads/Book1.xlsx")

Define a function to color the markers based on ship type

color_by_shiptype <- function(ShipType) {
if (ShipType == "Product tanker") {
return("red")
} else if (ShipType == "Container ship") {
return("blue")
} else if (ShipType == "Fishing vessel") {
return("green")
} else if (ShipType == "Chemical tanker") {
return("orange")
} else {
return("black")
}
}

Create a leaflet map object

map <- leaflet() %>% addTiles()

Add markers to the map based on the data from Excel sheet

for (i in 1:nrow(data)) {
map <- addCircleMarkers(map,
lat = data$Latitude[i],
lng = data$Longitude[i],
popup = paste(data$Name[i], ": ", data$Date[i], data$ShipType[i]),
color = ~color_by_shiptype(data$ShipType[i]))
}

Display the map

map

Have a look at bottom the example here: Leaflet for R - Markers (rstudio.github.io)

The relevant code, which you'll need to adapt to yours:

# Create a palette that maps factor levels to colors
pal <- colorFactor(c("navy", "red"), domain = c("ship", "pirate"))

leaflet(df) %>% addTiles() %>%
  addCircleMarkers(
    radius = ~ifelse(type == "ship", 6, 10),
    color = ~pal(type),
    stroke = FALSE, fillOpacity = 0.5
  )

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.