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.


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") {
} else if (ShipType == "Container ship") {
} else if (ShipType == "Fishing vessel") {
} else if (ShipType == "Chemical tanker") {
} else {

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


Have a look at bottom the example here: Leaflet for R - Markers (

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() %>%
    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.