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
At time of writing, Renjin (a Java-based R interpreter) does not have a lot of packages to help solve this problem. Here is an implementation that does not depend on extra packages.
# Computes the distance between two locations in meters. This uses an online
# map API and therefore an Internet connection is required for an accurate
# result. If no connection is found, this will use the Haversine formula
# to provide a rough estimate for the distance.
#
# @param src The source latitude and longitude.
# @param dst The destination latitude and longitude.
# @param mode Driving, cycling, walking, etc.
distance <- function( lat1, lon1, lat2, lon2, mode = 'driving' ) {
lat1 = as.numeric( lat1 )
lon1 = as.numeric( lon1 )
lat2 = as.numeric( lat2 )
lon2 = as.numeric( lon2 )
# Create the URL to use to get the distance data.
url = paste0(
'https://maps.googleapis.com/maps/api/distancematrix/xml?',
'origins=', lat1,
',', lon1,
'&destinations=', lat2,
',', lon2,
'&mode=', mode,
'&sensor=false'
)
tryCatch({
# Download the XML document with distance information.
xml = readLines( url )
# The element immediately follows the distance element.
value = xml[ grep( "", xml ) + 1 ]
# Obtain the distance in meters.
meters = sub( ".*>(.*?)<.*", "\\1", value )
# Return the distance.
as.numeric( meters )
},
warning = function( w ) {
haversine( lat1, lon1, lat2, lon2 )
},
error = function( e ) {
haversine( lat1, lon1, lat2, lon2 )
})
}
# Computes distance using Haversine formula.
#
# Returns the result in meters.
haversine <- function( lat1, lon1, lat2, lon2, radius = 6371 ) {
# Convert decimal degrees to radians
lon1 = lon1 * pi / 180
lon2 = lon2 * pi / 180
lat1 = lat1 * pi / 180
lat2 = lat2 * pi / 180
# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * atan2(sqrt(a), sqrt(1-a))
return( radius * c * 1000 )
}
Output:
distance( '44.5646', '-123.2620', '41.2861', '-124.0902' )
[1] 495892
distance( 44.5646, -123.2620, 41.2861, -124.0902, mode='walking' )
[1] 487715
Conversion from meters to feet is an exercise for the reader.