This code provides an example where you can take a CSV of points with a unique ID for each line (I use the ids “one” and “two” to map two lines), and map them with Leaflet in R. You could use rgdal to save these as GeoJSON or Shapefile or any other spatial format.
library(leaflet)
library(sp)
Here I load the sample points posted on stack overflow. Then I randomly assign each point to be either in line “one” or line “two”
d <- read.csv("./sample-points2.csv")
d$id <- data.frame(id = factor(
ifelse(runif(dim(d)[1]) > 0.75, "one", "two"),
c("one", "two")
))
head(d)
## longitude latitude id
## 1 -119.2875 37.16585 two
## 2 -119.2875 37.16497 one
## 3 -119.2875 37.16497 two
## 4 -119.2875 37.16497 two
## 5 -119.2875 37.16585 two
## 6 -119.2875 37.16497 one
d <- SpatialPointsDataFrame(coords=d[,1:2],
data = d[,3])
summary(d)
## Object of class SpatialPointsDataFrame
## Coordinates:
## min max
## longitude -119.28760 -119.28718
## latitude 37.16478 37.16585
## Is projected: NA
## proj4string : [NA]
## Number of points: 74
## Data attributes:
## id
## one:18
## two:56
Here is a map of the inital points
basemap <- leaflet() %>% addProviderTiles("Esri.WorldImagery", options = tileOptions(maxZoom = 22))
basemap %>% addCircleMarkers(data=d)
first this code subsets the two lines. Then it turns these lines into a SpatialLinesDataFrame
d1 <- subset(d, d@data$id=="one")
d2 <- subset(d, d@data$id=="two")
Sl1 = Line(d1)
Sl2 = Line(d2)
S1 = Lines(list(Sl1), ID="one")
S2 = Lines(list(Sl2), ID="two")
Sl = SpatialLinesDataFrame(SpatialLines(list(S1,S2)),
data=data.frame(id=c("one","two")),
match.ID=FALSE)
The code assigns different line colors to each line and then maps them again using Leaflet
lineColor <- colorFactor(rainbow(length(Sl@data$id)) , Sl@data$id)
basemap %>% addPolylines(data=Sl, color= ~lineColor(id))