2017-02-03 4 views
3

Я создаю Shiny панели с dataframe от запуска долготы/широты и конца долготы/широт cooridnated что я изобразил в R с помощью leaflet package:Рисования пути путешествия с использованием листовки в R

`m=leaflet()%>% 
     addTiles() %>% 
     addMarkers(lng=(data$Start_long[i:j]), lat=(data$Start_lat[i:j]),popup="Start") %>% 
     addCircleMarkers(lng=(data$End_long[i:j]), lat=(data$End_lat[i:j]),popup="End",clusterOptions=markerClusterOptions())` 

Я задавался вопрос если бы был способ присоединиться к началу и концу, координируемым маршрутами общественного транспорта (возможно, через API-интерфейс google или внутрибиблиотечные функции или, если это не удалось, соединить координаты по прямой?

ответ

5

Вы можете использовать мой googleway пакет и получить направления/маршруты, и построить его на карте Google

Чтобы использовать API Google, вам нужен правильный ключ для каждого API вы хотите использовать. В этом случае вы будете хотеть directions key, и для построения карты вы хотите maps javascript key

(Вы можете создать один ключ и включить его для обоих API, если вы хотите)

Для вызова API Directions и построить его в R, вы можете сделать

library(googleway) 

api_key <- "your_directions_api_key" 
map_key <- "your_maps_api_key" 

## set up a data.frame of locations 
## can also use 'lat/lon' coordinates as the origin/destination 
df_locations <- data.frame(origin = c("Melbourne, Australia", "Sydney, Australia"), 
          destination = c("Sydney, Australia", "Brisbane, Australia"), 
          stringsAsFactors = F) 


## loop over each pair of locations, and extract the polyline from the result 
lst_directions <- apply(df_locations, 1, function(x){ 
    res <- google_directions(key = api_key, 
          origin = x[['origin']], 
          destination = x[['destination']]) 

    df_result <- data.frame(origin = x[['origin']], 
          destination = x[['destination']], 
          route = res$routes$overview_polyline$points) 
    return(df_result) 

}) 

## convert the results to a data.frame 
df_directions <- do.call(rbind, lst_directions) 

## plot the map 
google_map(key = map_key) %>% 
    add_polylines(data = df_directions, polyline = "route") 

enter image description here


и точно так же в блестящей приложение

library(shiny) 
library(shinydashboard) 
library(googleway) 

ui <- dashboardPage(
    dashboardHeader(), 
    dashboardSidebar(), 
    dashboardBody(
    textInput(inputId = "origin", label = "Origin"), 
    textInput(inputId = "destination", label = "Destination"), 
    actionButton(inputId = "getRoute", label = "Get Rotue"), 
    google_mapOutput("myMap") 
) 
) 

server <- function(input, output){ 

    api_key <- "your_directions_api_key" 
    map_key <- "your_maps_api_key" 

    df_route <- eventReactive(input$getRoute,{ 

    print("getting route") 

    o <- input$origin 
    d <- input$destination 

    return(data.frame(origin = o, destination = d, stringsAsFactors = F)) 

    }) 


    output$myMap <- renderGoogle_map({ 

    df <- df_route() 
    print(df) 
    if(df$origin == "" | df$destination == "") 
     return() 

    res <- google_directions(key = api_key, 
          origin = df$origin, 
          destination = df$destination) 

    df_route <- data.frame(route = res$routes$overview_polyline$points) 

    google_map(key = map_key) %>% 
     add_polylines(data = df_route, polyline = "route") 
    }) 
} 

shinyApp(ui, server) 

enter image description here

1

Вы можете addPolylines() на карту.

В качестве аргументов требуется два вектора, один для лат и один для lng, где каждая строка является «путевой точкой».
Трудно вам помочь, не зная структуры ваших данных. MRE:

library(leaflet) 
cities <- read.csv(textConnection(" 
City,Lat,Long,Pop 
Boston,42.3601,-71.0589,645966 
Hartford,41.7627,-72.6743,125017 
New York City,40.7127,-74.0059,8406000 
Philadelphia,39.9500,-75.1667,1553000 
Pittsburgh,40.4397,-79.9764,305841 
Providence,41.8236,-71.4222,177994 
")) 

leaflet() %>% 
    addTiles() %>% 
    addPolylines(lat = cities$Lat, lng = cities$Long) 
+0

я попытался полилинии, однако все линии были объединены. Данные составляют в значительной степени 5 столбцов, название места и стенд/конец long и lats –

+0

Это действительно зависит от того, как структурированы ваши данные. Pls обеспечивает воспроизводимый пример. – GGamba

+0

Надеюсь, что это помогает: Начало Конец Дата Startlat Startlon Endlat Endlon Харвуд Бери 17/05/16 53.5984 -2.38731 53.59125 -2.29713 Harwood Уиган 17/05/16 53,5984 -2,38731 -2,63202 53,54582 и т.д. и т.п. –

Смежные вопросы