Reputation: 677
My question is similar (basically the same) to the previous asked one: Draw All Lines Between Points
But I would like to have a solution using leaflet in R. Is it possible to do this using leaflet? The addPolylines()
function works as connecting all of the consecutive points in a dataframe. As the example dataset below, it is easy to connect all points by sequence, but how to draw all the possible segments between those five points?
I would like to see a general solution with leaflet that I can apply on scenarios with more points. Many thanks!
locations <- data.frame(Long = c(76,75,73,72,74,76), Lat = c(43,40,40,43,45,43))
leaflet("locations") %>%
addTiles() %>%
addPolylines(lng = locations$Long,
lat = locations$Lat)
Upvotes: 1
Views: 823
Reputation: 6106
It can be broken down into 2 steps:
library(leaflet)
library(tidyr)
library(dplyr)
library(purrr)
locations <- data.frame(Long = c(76,75,73,72,74,76), Lat = c(43,40,40,43,45,43))
# get unique coordinates
locations_distinct <- locations %>%
distinct_all()
# get all combinations between any two points
combs <- combn(1:nrow(locations_distinct),2,simplify = FALSE)
# get pairs of coordinates
locations_paris <- map_df(combs,function(x){
df <- bind_cols(
locations_distinct[x[1],],locations_distinct[x[2],]
)
colnames(df) <- c("Long","Lat","Long1","Lat1")
return(df)
})
How Do I connect two coordinates with a line using Leaflet in R
map <- leaflet(locations_paris) %>%
addTiles()
for(i in 1 : nrow(locations_paris)){
map <- map %>%
addPolylines(
lng = c(locations_paris$Long[i],locations_paris$Long1[i]),
lat = c(locations_paris$Lat[i],locations_paris$Lat1[i])
)
}
map
Upvotes: 3