Home > database >  How Do I connect two separate routes with a line using Leaflet?
How Do I connect two separate routes with a line using Leaflet?

Time:12-17

Observation originlat originLong endLat endLong
A 31.36445 121.60415 33.7372 -118.22531
A 41.3459 2.17599 20.14076 57.48244

These are the coords. When I select A it just connects all points together. I want the first 2 points connected separately as well as the second ones.

leaflet() %>%
      addTiles() %>%
      addCircleMarkers(
        lng = c(originLong, endLong),
        lat = c(originlat, endLat)
      ) %>%
      addPolylines( lng = c(originLong, endLong),
                    lat = c(originlat, endLat))})

CodePudding user response:

I have saved the data in a data frame called df. In order to show multiple lines in the leaflet map, you can loop over the values in your data frame and call addPolyLines() from within.

The code will look like this:


map <- leaflet() %>%
  addTiles() %>%
  addCircleMarkers(
    lng = c(df$originLong, df$endLong),
    lat = c(df$originlat, df$endLat)
  ) 

for (i in 1:nrow(df)) {
  map <- map %>% addPolylines(lng = c(df[i,]$originLong, df[i,]$endLong),
                              lat = c(df[i,]$originlat, df[i,]$endLat))
}

The output will look like this:

enter image description here

  • Related