Search code examples
rleaflet

Leaflet plot with GPS coordinates in R


I want to display a CSV file via its coordinates using leaflet in R. I think leaflet is not being able to pick up the coordinates correctly, how can I fix this?

Sample Data

Point Name X        Y
1     A    1393959  406726.6
2     B    1392820  407719.7
3     C    1394466  405740.5 
4     D    1393543  407094.7
5     E    1395119  405969.7
6     F    1393557  406747.5

Code

library(tidyverse)
library(leaflet)

map_data = df
map_data$popup = paste("<b>Location #: </b>", map_data$Point,
                       "<br>", "<b>Longitude: </b>", map_data$X,
                    "<br>", "<b>Latitude: </b>", map_data$Y,
                    "<br>", "<b>Desciption </b>", map_data$Name)
                    
                    
leaflet(map_data, width = "100%") %>% addTiles() %>%
  addTiles(group = "OSM (default)") %>%
  addProviderTiles(provider = "Esri.WorldStreetMap",group = "World StreetMap") %>%
  addProviderTiles(provider = "Esri.WorldImagery",group = "World Imagery") %>%
  addMarkers(lng = ~X, lat = ~Y, popup = map_data$popup, clusterOptions = markerClusterOptions())

Current Plot

enter image description here


Solution

  • First convert the df into an sf object. Define the CRS which in my case is 2271. Reproject to 4326 to make it work with leaflet and run the rest of the code.

    library(tidyverse)
    library(sf)
    library(sfheaders)
    library(leaflet)
    
    # Convert df to sf
    df_sf = st_as_sf(x = df,                         
               coords = c("X", "Y"),
               crs = 2271)
    
    # Reproject to WGS84
    df_sf = st_transform(df_sf , 4326)
    df_sf = sf_to_df(rocks_wgs_sf, fill = T) 
    
    # Create the map
    map_data = df
    map_data$popup = paste("<b>Location #: </b>", map_data$Point,
                           "<br>", "<b>Longitude: </b>", map_data$X,
                        "<br>", "<b>Latitude: </b>", map_data$Y,
                        "<br>", "<b>Desciption </b>", map_data$Name)
                        
                        
    leaflet(map_data, width = "100%") %>% addTiles() %>%
      addTiles(group = "OSM (default)") %>%
      addProviderTiles(provider = "Esri.WorldStreetMap",group = "World StreetMap") %>%
      addProviderTiles(provider = "Esri.WorldImagery",group = "World Imagery") %>%
      addMarkers(lng = ~X, lat = ~Y, popup = map_data$popup, clusterOptions = markerClusterOptions())