Leaflet htmlwidget for R

GeoJSON

If your data is in GeoJSON format, you can either convert it into sp classes using rgdal::readOGR and then use the marker and shape functions to add them; or use the addGeoJSON() function, for more convenient but less expressive handling.

The addGeoJSON() function accepts GeoJSON data in either parsed (nested lists) or stringified (single-element character vector) format.

You can hard-code the style into the GeoJSON data by adding a style object to the top level GeoJSON object, or annotating each feature’s property object with a style: {...} object. Here’s an example that sets both global styles and per-feature styles.

library(jsonlite)

# From http://data.okfn.org/data/datasets/geo-boundaries-world-110m
geojson <- readLines("json/countries.geojson", warn = FALSE) %>%
  paste(collapse = "\n") %>%
  fromJSON(simplifyVector = FALSE)

# Default styles for all features
geojson$style = list(
  weight = 1,
  color = "#555555",
  opacity = 1,
  fillOpacity = 0.8
)

# Gather GDP estimate from all countries
gdp_md_est <- sapply(geojson$features, function(feat) {
  feat$properties$gdp_md_est
})
# Gather population estimate from all countries
pop_est <- sapply(geojson$features, function(feat) {
  max(1, feat$properties$pop_est)
})

# Color by per-capita GDP using quantiles
pal <- colorQuantile("Greens", gdp_md_est / pop_est)
# Add a properties$style list to each feature
geojson$features <- lapply(geojson$features, function(feat) {
  feat$properties$style <- list(
    fillColor = pal(
      feat$properties$gdp_md_est / max(1, feat$properties$pop_est)
    )
  )
  feat
})

# Add the now-styled GeoJSON object to the map
leaflet() %>% addGeoJSON(geojson)

See Leaflet’s path options for available style properties.