maluwalmk - 8 months ago 40
R Question

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

I am trying to use Leaflet package in R to draw a amp and connect the markers given the latitude and longitude information in the table below.

```

| Observation | InitialLat | InitialLong | NewLat    | NewLong   |
|-------------|------------|-------------|-----------|-----------|
| A           | 62.469722  | 6.187194    | 51.4749   | -0.221619 |
| B           | 48.0975    | 16.3108     | 51.4882   | -0.302621 |
| C           | 36.84      | -2.435278   | 50.861822 | -0.083278 |
| D           | 50.834194  | 4.298361    | 54.9756   | -1.62179  |
| E           | 50.834194  | 4.298361    | 54.9756   | -1.62179  |
| F           | 50.834194  | 4.298361    | 51.4882   | -0.302621 |
| G           | 47.460427  | -0.530804   | 51.44     | -2.62021  |
| H           | 51.5549    | -0.108436   | 53.4281   | -1.36172  |
| I           | 51.5549    | -0.108436   | 52.9399   | -1.13258  |
| J           | 51.5549    | -0.108436   | 51.889839 | -0.193608 |
|             | 51.5549    | -0.108436   | 52.0544   | 1.14554   |

```

I want to draw lines from an initial point given by the coordinates in the
`InitialLat`
and
`InitialLong`
columns to an end point given by the
`NewLat`
and
`NewLong`
columns.

Here is my current R code which only draws the markers on the map.

```

library(leaflet)

```

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()%>%