I try to calculate distance between a location in New York City with the zipcode 10027 and Beijing, China using mapdist()
function, but it returns NA
. Is there anyone know how it works?
> mapdist(as.numeric(geocode("10027")),as.numeric(geocode("beijing,china")))
from
1 500 Riverside Dr, New York, NY 10027, USA
to
1 Bei Jing Shi Ren Min Zheng Fu, Dongcheng Qu, Beijing Shi, China
km miles minutes hours
1 NA NA NA NA `
If you look at R's help option it gives you a nice example of what is going on.
#import ggmap
library(ggmap)
#get set of longitudinal and latitudinal coordinates
(wh <- as.numeric(geocode("the white house, dc")))
(lm <- as.numeric(geocode("lincoln memorial washington dc")))
You have to also set a mode for walking, bicycling or driving.
mapdist(wh, lm, mode = "walking")
As Alistaire mentions, for geographic distances, you must calculate distances according to the earth's spherical shape. Even though the earth isn't perfectly circular, there are formulas that are reasonably accurate.
The following is a formula I took directly from this website:
http://www.r-bloggers.com/great-circle-distance-calculations-in-r/
gcd.hf <- function(long1, lat1, long2, lat2) {
R <- 6371 # Earth mean radius [km]
delta.long <- (long2 - long1)
delta.lat <- (lat2 - lat1)
a <- sin(delta.lat/2)^2 + cos(lat1) * cos(lat2) * sin(delta.long/2)^2
c <- 2 * asin(min(1,sqrt(a)))
d = R * c
return(d) # Distance in km
}
I'd read the link if this you are asking for geographical distance.