Chuan
Chuan

Reputation: 677

How to draw all possible line segments between existing points using leaflet in R

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

Answers (1)

Yifu Yan
Yifu Yan

Reputation: 6106

It can be broken down into 2 steps:

  1. Create a data frame which contains all combinations between coordinates.
  2. Draw lines between each pair of coordinates. See How Do I connect two coordinates with a line using Leaflet in R

Step 1

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)
})

Step 2

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

enter image description here

Upvotes: 3

Related Questions