How Do I connect two coordinates with a line using Leaflet in R

Here is an alternative way using the leaflet package. I just took two data points in your data for the purpose of demonstration.

mydf <- data.frame(Observation = c("A", "B"),
                   InitialLat = c(62.469722,48.0975),
                   InitialLong = c(6.187194, 16.3108),
                   NewLat = c(51.4749, 51.4882),
                   NewLong = c(-0.221619, -0.302621),
                   stringsAsFactors = FALSE)

I changed the format of mydf and create a new data frame for leaflet. You can reshape your data in various ways.

mydf2 <- data.frame(group = c("A", "B"),
                    lat = c(mydf$InitialLat, mydf$NewLat),
                    long = c(mydf$InitialLong, mydf$NewLong))

#  group      lat      long
#1     A 62.46972  6.187194
#2     B 48.09750 16.310800
#3     A 51.47490 -0.221619
#4     B 51.48820 -0.302621

library(leaflet)
library(magrittr)

leaflet()%>%
addTiles() %>%
addPolylines(data = mydf2, lng = ~long, lat = ~lat, group = ~group)

I trimmed the interactive map I got. Please see the map below. Although two lines are connected in this image, they are separated. If you run the code and zoom in, you will see that the two lines are separated.

enter image description here

Leave a Comment