R que R

Leaflet maps (Part II)

Wed, Apr 8, 2020
R
#leaflet #raster #geographic coordinates #mapas #maps


Packages



# PACKAGES / LIBRARIES:


library(tidyverse)
library(leaflet)
library(readxl)
library(leaflet.providers)
library(raster)
library(sf)

Intro

Leaflet is an open source JavaScript library used to build web mapping applications. It creates embedding maps with tiled base layers, interactive panning and zooming and feature layers.


The {leaflet} R package allows to integrate and control Leaflet maps in R and to create maps from the R console or from RStudio. {leaflet} also provides interactive panning and zooming and allows rendering spatial objects from the {sp} or {sf} packages or from dataframes with latitude and longitude coordinates. There is also a leaflet plugins repository that you can use to add more features/plugins to your maps.


This second post will expose how to create choropleth maps using the {leaflet} package. As an example, it will show two choropleth maps of India at different administrative levels: States (& Union Territories) and Districts. There is also a Talukas (or Teshils) level (level = 3) available but we will not create a map representing this third level in this post as it will slow it down too much. Notice that labels, pop-up tables and polygon highlights have been customized.


Level 1. State / Union Territory



IND_1 <- getData("GADM", country= "IND", level=1)

pal <- colorFactor(
  palette = "Paired",
  domain = IND_1@data$NAME_1)

IND_1  %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldShadedRelief) %>%
  addPolygons(weight = 1,
              stroke = TRUE,
              color = "white",
              fillColor = ~pal(NAME_1),
              fillOpacity = 0.7,
              dashArray = "3",
              label = ~NAME_1,
              popup = ~paste("State/Union Territory:", NAME_1,
                             "<br/>",
                             "Country:", NAME_0),
              highlight = highlightOptions(
                weight = 2,
                dashArray = "",
                color = "grey",
                bringToFront = TRUE
              ))


Level 2. Districts



IND_2 <- getData("GADM", country= "IND", level=2)

IND_2  %>%
  leaflet() %>%
  addProviderTiles(providers$Esri.WorldShadedRelief) %>%
  addPolygons(weight = 1,
              stroke = TRUE,
              color = "white",
              fillColor = ~pal(NAME_1),
              fillOpacity = 0.7,
              dashArray = "3",
              label = ~NAME_2,
              popup = ~paste("District:", NAME_2,
                             "<br/>",
                             "State:", NAME_1,
                              "<br/>",
                             "Country:", NAME_0),
              highlight = highlightOptions(
                weight = 2,
                dashArray = "",
                color = "grey",
                bringToFront = TRUE
              ))



Click here to see the map.