ggmap route finding - doesn't stay on roads

后端 未结 2 696
醉酒成梦
醉酒成梦 2021-02-03 10:15

I am trying to map a route using the route() function in ggmap. My problem is that the route doesn\'t stay on the roads. Is there something that my route_df <- route(or

2条回答
  •  猫巷女王i
    2021-02-03 10:37

    You can use my googleway package

    • get the directions
    • decode the polyline (if required)
    • plot the route on a Google Map, either as an encoded polyline, or the decoded points

    library(googleway)
    
    apiKey <- 'your_api_key'
    mapKey <- 'your_maps_api_key'
    
    res <- google_directions(origin = "Tinsletown, Vancouver, BC", 
                            destination = "Science World, Vancouver, BC",
                            key = apiKey)
    

    The polyline is in res$routes$overview_polyline$points

    You can decode the polyline if you want

    pl <- res$routes$overview_polyline$points
    decode_pl(pl)
    #         lat       lon
    # 1  49.28025 -123.1076
    # 2  49.27969 -123.1076
    # 3  49.27823 -123.1076
    # 4  49.27711 -123.1077
    # 5  49.27707 -123.1043
    

    But you don't have to, you can plot the line directly

    df <- data.frame(polyline = pl)
    
    google_map(key = mapKey, search_box = T) %>%
        add_polylines(data = df, polyline = "polyline")
    

    Note

    • It looks like the origin doesn't exist or has moved since the question was asked

提交回复
热议问题