Home > OS >  plot a map using lat and lng coordinates in R
plot a map using lat and lng coordinates in R

Time:11-26

My data set has 4 columns which are station_name, station_lat, station_lng and count.This is the example of my data set.

stations <- data.frame(station = c("StreeterDr", "MichiganAve", "WellsSt"), lat = c(41.89228, 41.90096, 41.91213), lng = c(-87.61204, -87.62378, -87.63466), count = c(2300, 5678, 3452))

I want to plot these coordinates on maps. Referring previous post on this topic I tried this code. But it's not working.

install.packages(c("leaflet", "sp")) 
library(leaflet)
library(leaflet)

lon <- stations$start_lng
lat <- stations$start_lat
df <- as.data.frame(cbind(lon,lat))

coordinates(df) <- ~lon lat
leaflet(df) %>% addMarkers() %>% addTiles()

CodePudding user response:

Stating to R which columns are xy is not sufficient. You need to convert your data.table to an sf object as well and state which geographic coordinate system you use.

#object with your data


#state which columns are lon and lat
coordinates(dt) <- ~lng lat

#convert to sf object
dt <- st_as_sf(dt)

#set crs (WSG1984 seems to be used here)
st_crs(dt) <- 4326

#create leaflet
leaflet(dt) %>% addMarkers() %>% addTiles()

enter image description here

  • Related