1

I am trying to show the data that I have in a data frame on a map by using leaflet library, but not sure how.

geom <- c('LINESTRING(174.7698950000 -41.3435950000,174.7698040000 -41.3434660000,174.7714690000 -41.3395070000)')
description <- c('labelA')
df <- data.frame(geom, description)
leaflet(df) %>%
  addTiles() %>%
  addPolylines(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 1,
               fillColor = factor('description'),
               label = ~paste0('description', ": ", formatC(description, big.mark = ","))) 

Error I am getting:

Error in polygonData.default(data) : 
 Don't know how to get path data from object of class data.frame

Please let me know how I can improve the question instead of down voting

1 Answer 1

1

You are only missing one step. What you have is a standard data frame, which Leaflet cannot interpret as a spatial object.

You first need to convert your df to a spatial object: the sf package is excellent for that. Your leaflet code was masking the stroke so the line was not showing: I changed that and set the color to red.

library(leaflet)
library(sf)

geom <- c('LINESTRING(174.7698950000 -41.3435950000,174.7698040000 -41.3434660000,174.7714690000 -41.3395070000)')
description <- c('labelA')


df <- data.frame(geom, description) # ordinary data frame

df <- st_as_sf(df, wkt = "geom") # convert to spatial data frame

leaflet(df) %>%
   addTiles() %>%
   addPolylines(stroke = TRUE, 
                smoothFactor = 0.3,
                fillOpacity = 1,
                color = "red",
                label = ~paste0('description', ": ", formatC(description, big.mark = ",")))

leaflet screenshot

Note that you may have to set the CRS of your object so that it is projected correctly by Leaflet and shows in the right place. Leaflet uses WGS84 (EPSG: 4326) but your data might be recorded in something else. You can adapt this:

df <- st_set_crs(df, 27700)  # this would set the CRS to the British National Grid  
df <- st_transform(df, 4326) # reproject in WGS84

You can search for EPSG codes here. Hope that helps.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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