Adding Curved Flight path using R's Leaflet Pa

2019-01-13 22:50发布

问题:

Currently I'm able to draw a straight line between countries using the following code:

library(leaflet) 
leaflet() %>% addTiles() %>% addPolylines(lat=c(38.8833, 35.00), lng=c(-77.0167, 103.00))

What I'm trying to produce is a more realistic flight path, where the straight line is actually curved. Similar to this:

For the sake of this question, I'd like to tailor the answer within the Leaflet package. Any help would be much appreciated.

回答1:

following up on mrub, just pass the object you get from gcIntermediate to leaflet. something like this:

library(leaflet)
library(geosphere)
gcIntermediate(c(5,52), c(-120,37),
               n=100, 
               addStartEnd=TRUE,
               sp=TRUE) %>% 
leaflet() %>% 
addTiles() %>% 
addPolylines()


回答2:

You are looking for something like this: How to draw great circles In the answer, the package geosphere with the function gcIntermediate() is used:

inter <- gcIntermediate(c(lon_1, lat_1), c(lon_2, lat_2), n=50, addStartEnd=TRUE)
lines(inter)


回答3:

While trying to show more than one line by the method posted by einar, I couldn't show both of them at once. After much digging, I came across this and this posts. Here is a small code for two different lines.

library(geosphere)
library(leaflet)
library(dplyr)

lat_ny <- 40.73
lng_ny <- -73.9
lat_del <- 28.63
lng_del <- 77.21
lng_ca <- -121.6406
lat_ca <- 39.16414

inter1 <- gcIntermediate(c(lng_ny, lat_ny), c(lng_del, lat_del), n=10, addStartEnd=TRUE, sp = TRUE, breakAtDateLine = TRUE)
lines(inter1)

inter2 <- gcIntermediate(c(lng_ca, lat_ca), c(lng_del, lat_del), n=10, addStartEnd=TRUE, sp = TRUE, breakAtDateLine = TRUE)
lines(inter2)

inters <- c(inter1,inter2)

ll0 <- lapply( inters , function(x) `@`(x , "lines") )
ll1 <- lapply( unlist( ll0 ) , function(y) `@`(y,"Lines") )
Sl <- SpatialLines( list( Lines( unlist( ll1 ) , ID = 1 ) ) )

leaflet(Sl) %>% addTiles() %>% addPolylines()

Hardcoding latitude and longitude is not a good idea, but as I had to pick only top 5 connect place, I did not devote much time for indexing of a list. Also I am still to check if it integrates with Shiny.



标签: r leaflet