Getting driving distance between two points (lat, lon) using R and Google Map API

前端 未结 5 591
失恋的感觉
失恋的感觉 2021-01-30 18:29

I am trying to get the driving distance between two points with lat/lon given. I can manually put them into google map and get the driving distance but I want to do all this pr

5条回答
  •  天涯浪人
    2021-01-30 19:14

    I've written the googleway package to do this using Google Maps API

    In particular, the google_directions() function will give you driving distances, directions, routes, legs, steps etc. And the google_distance() function will give you a distance matrix for all the origins/destinations

    You need a Google API key to use their API

    library(googleway)
    
    ## your valid API key
    key <- "your_api_key_here"
    
    directions <- google_directions(origin = c(37.193489,-121.07395),
                                    destination = c(37.151616,-121.046586),
                                    key = key, 
                                    simplify = T)
    
    directions$routes$legs
    # [[1]]
    # distance.text distance.value duration.text duration.value duration_in_traffic.text duration_in_traffic.value                 end_address
    # 1        5.2 km           5250        3 mins            161                   3 mins                       156 I-5, Gustine, CA 95322, USA
    # end_location.lat end_location.lng               start_address start_location.lat start_location.lng
    # 1         37.15162        -121.0466 I-5, Gustine, CA 95322, USA           37.19349           -121.074
    # steps
    # 1 5.2 km, 5250, 3 mins, 161, 37.1516163, -121.0465852, Head southeast on I-5 S, ij_bFfg~aVpBgA`DkB~FeDbIwEpEgCtaAsj@nAs@lDqBxIaF~FgDlHcEjC{AdFuCrBkAhC{A|A{@|A}@bAk@rBkArBkA|A{@`DiB|A}@vDwBdAm@dAm@rBkA|A{@zA{@~J{FpC_B~A}@tBkAjHeEvGuDlMmHtBkAVO, 37.1934864, -121.0739565, DRIVING
    #   traffic_speed_entry via_waypoint
    #   1                NULL         NULL
    
    
    
    google_distance(origins = list(c(37.193489,-121.07395)),
                    destinations = list(c(37.151616,-121.046586)),
                    key = key, 
                    simplify = T,
                    units = "imperial")
    
    # $destination_addresses
    # [1] "I-5, Gustine, CA 95322, USA"
    # 
    # $origin_addresses
    # [1] "I-5, Gustine, CA 95322, USA"
    # 
    # $rows
    # elements
    # 1 3.3 mi, 5250, 3 mins, 161, 3 mins, 157, OK
    # 
    # $status
    # [1] "OK"
    

    Given the google_directions() function returns a polyline (the line you get on Google Maps when you search for a route), we can plot it on a Google Map

    key <- 'your_map_api_key'
    
    df_route <- decode_pl(directions$routes$overview_polyline$points)
    
    google_map(data = df_route, key = key, height = 800, search_box = T) %>%
        add_markers()
    ## or you can use `add_polyline()` to view the entire line
    

提交回复
热议问题