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

前端 未结 5 2004
半阙折子戏
半阙折子戏 2020-11-28 09:27

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          


        
5条回答
  •  悲&欢浪女
    2020-11-28 09:53

    I know this was asked a year ago but I had the same question and figured out how to do it in leaflet.

    You are first going to have to adjust your dataframe because addPolyline just connects all the coordinates in a sequence. I will make a dataframe with 4 separate ending locations for the purpose of this demonstration.

    dest_df <- data.frame (lat = c(41.82, 46.88, 41.48, 39.14),
                       lon = c(-88.32, -124.10, -88.33, -114.90)
                      )
    

    Next, I am going to create a data frame with the central location of the same size (4 in this example) of the destination locations. I will explain why I'm doing this soon

    orig_df <- data.frame (lat = c(rep.int(40.75, nrow(dest_df))),
                       long = c(rep.int(-73.99,nrow(dest_df)))
                      )
    

    The reason why I am doing this is because the addPolylines feature will connect all the coordinates in a sequence. The way to get around this in order to create the image you described is by starting at the starting point, then going to destination point, and then back to the starting point, and then to the next destination point. In order to create the dataframe to do this, we will have to interlace the two dataframes by placing in rows as such:

    starting point - destination point 1 - starting point - destination point 2 - and so forth...

    The way I will do is create a key for both data frames. For the origin dataframe, I will start at 1, and increment by 2 (e.g., 1 3 5 7). For the destination dataframe, I will start at 2 and increment by 2 (e.g., 2, 4, 6, 8). I will then combine the 2 dataframes using a UNION all. I will then sort by my sequence to make every other row the starting point. I am going to use sqldf for this because that is what I'm comfortable with. There may be a more efficient way.

    orig_df$sequence <- c(sequence = seq(1, length.out = nrow(orig_df), by=2))
    dest_df$sequence <- c(sequence = seq(2, length.out = nrow(orig_df), by=2))
    
    library("sqldf")
    q <- "
    SELECT * FROM orig_df
    UNION ALL
    SELECT * FROM dest_df
    ORDER BY sequence
    "
    poly_df <- sqldf(q)
    

    The new dataframe looks like this Notice how the origin locations are interwoven between the destination

    And finally, you can make your map:

    library("leaflet")
    leaflet() %>%
      addTiles() %>%
    
      addPolylines(
        data = poly_df,
        lng = ~lon, 
        lat = ~lat,
        weight = 3,
        opacity = 3
      ) 
    

    And finally it should look like this I hope this helps anyone who is looking to do something like this in the future

提交回复
热议问题