Calculating the distance between ZIP Codes in R wi

2019-07-13 18:09发布

问题:

I am trying to use the mapdist function in R which relies on the Google Geocoding API. There are many pairs of ZIPs for which the mapdist function results in NA values. For instance:

mapdist('19111', '19187')
by using this function you are agreeing to the terms at :
http://code.google.com/apis/maps/documentation/distancematrix/

Information from URL : http://maps.googleapis.com/maps/api/distancematrix/json?origins=19111&destinations=19187&mode=driving&sensor=false
   from    to km miles minutes hours
1 19111 19187 NA    NA      NA    NA

But when I go into the Google Maps website it easily finds the correct answer which is about 13 miles. Does anyone know why this is happening? For many other pairs of ZIPs the function works perfectly. Thanks.

回答1:

It could be that the zip code on its own is ambiguous. If you include 'USA' in the search string it works

library(ggmap)

mapdist(from = c("19111, USA"), to = c("19187, USA"))


#         from         to     m    km    miles seconds  minutes     hours
# 1 19111, USA 19187, USA 21420 21.42 13.31039    1976 32.93333 0.5488889

Or

library(googleway)

set_key("your_api_key")

google_distance(origins = c("19111, USA"), 
                destinations = c("19187, USA"))

# $destination_addresses
# [1] "Philadelphia, PA 19187, USA"
# 
# $origin_addresses
# [1] "Philadelphia, PA 19111, USA"
# 
# $rows
# elements
# 1 21.4 km, 21420, 33 mins, 1976, 35 mins, 2101, OK
# 
# $status
# [1] "OK"


标签: r mapping