9

Very new to R's Leaflet package and have two spatial data frames.

1) An outline of a city 2) Its major highways

I wish to show both of these on the same map. I get how to do this with ggmap or tmap. I'm little confused when it comes to Leaflet.

Here is some code that takes public data:

toronto - an outline of the city all_roads - Toronto's road network

I then view each separately with Leaflet. How do I view multiple layers from different spatial data frames on the same map?

library(sf)
library(leaflet)

# Read in Toronto boundaries as a spatial data frame
# WGS84 latitude and longitude
# Data: https://www.toronto.ca/city-government/data-research-maps/open-data/open-data-catalogue/#4a30ca3e-70f0-bf79-1e76-459ebda8458c
toronto <- st_read("/Users.../torontoBoundary_wgs84/citygcs_regional_mun_wgs84.shp")

# Read in street data
# (WGS84 projection)
# https://portal0.cf.opendata.inter.sandbox-toronto.ca/dataset/toronto-centreline-tcl-2/
all_roads <- st_read("/Users.../centreline_wgs84/CENTRELINE_WGS84.shp") 

# Just highways
xway <- filter(all_roads, FCODE_DESC == "Expressway")

map <- leaflet(data = hood_shp, options = leafletOptions(minZoom = 11, maxZoom = 13))
map %>% addPolygons(color = "#aaaaaa", weight = 1.0, smoothFactor = 0.5,
                    opacity = 1.0, fillOpacity = 0.7)

highway <- leaflet(data = xway)
highway %>% addPolygons(color = "brown", weight = 1.0, smoothFactor = 0.5,
                        opacity = 1.0, fillOpacity = 0.7)

1 Answer 1

9

simply, dont add the dataset in the leaflet() function:

leaflet() %>% addProviderTiles("CartoDB.Positron") %>%
    addPolygons(data=tonto, fillOpacity = 0.7,weight = 1.2, etc....)%>%
    addPolygons(data=xway, fillOpacity = 0.7,weight = 1.2etc....)

but you should also consider, perhaps along the line, having the basemap as something very simple such as:

output$map <- renderLeaflet({
    leaflet() %>%
      setView(lng = -3.8, lat = 54.8, zoom = 6) %>%
      addProviderTiles("CartoDB.DarkMatter", layerId = "basetile",options = providerTileOptions(minZoom = 6))
  })

and then you can add layers with observeEvents, buttons, tick boxes etc etc using leafletProxy();

leafletProxy("map", data = selectedstuff()) %>%
                        clearShapes() %>%
                        addPolygons(fillColor =  "red",
                                    popup = state_popup,
                                    color = "#BDBDC3",
                                    fillOpacity = 1,
                                    weight = 1)

have a google around for the latter, there's loads on the help pages and on this website

Rstudio leaflet help page for leafletproxy this answer (plus many more) might give you more insight into leafletproxy

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.