簡體   English   中英

使用R和Google Map API獲取兩點之間的距離(lat,lon)

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

我試圖通過給出lat / lon來獲得兩點之間的行駛距離。 我可以手動將它們放入谷歌地圖並獲得駕駛距離,但我想以編程方式完成所有這些操作。

我想JavaScript是最常用的語言。 但是,我不知道JavaScript,我相當熟悉使用R.我更喜歡在R中這樣做,因為我在R中進行所有數據分析。

我正在尋找沿着道路的距離而不是飛行距離。 經過幾個小時的嘗試,我在R中編寫了以下函數( 這個這一個幫助)。 你有沒有更好的方法來獲得這個功能或任何非常簡單的距離?

library(XML)
latlon2ft <- function(origin,destination)
{

xml.url <- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',origin,'&destinations=',destination,'&mode=driving&sensor=false')

xmlfile <- xmlTreeParse(xml.url)
xmltop = xmlRoot(xmlfile)
distance <- xmltop[['row']][[1]][5][1][['distance']][['value']][[1]]
distance <- as.numeric(unclass(distance)[['value']])
ft <- distance*3.28084 # FROM METER TO FEET
return(ft)
}

latlon2ft(origin='37.193489,-121.07395',destination='37.151616,-121.046586')

結果= 17224.41

你需要RCurl或同等學歷。

library(XML)
library(bitops)
library(RCurl)
latlon2ft <- function(origin,destination){
  xml.url <- paste0('http://maps.googleapis.com/maps/api/distancematrix/xml?origins=',origin,'&destinations=',destination,'&mode=driving&sensor=false')
  xmlfile <- xmlParse(getURL(xml.url))
  dist <- xmlValue(xmlChildren(xpathApply(xmlfile,"//distance")[[1]])$value)
  distance <- as.numeric(sub(" km","",dist))
  ft <- distance*3.28084 # FROM METER TO FEET
  return(ft)
}

latlon2ft(origin='37.193489,-121.07395',destination='37.151616,-121.046586')

結果:

[1] 17224.41

我創作了gmapsdistance包來做到這一點。 它可以在CRAN上使用。 您可以通過以下方式使用該功能:

results = gmapsdistance(origin = "38.1621328+24.0029257",
                        destination = "37.9908372+23.7383394",
                        mode = "walking") results
# $Time
# [1] 30025
# 
# $Distance
# [1] 39507
# 
# $Status
# [1] "OK"

您還可以包含原點和目的地的矢量,並獲得生成的距離矩陣。 它還支持方向,並有一堆選項:

results = gmapsdistance(origin = c("Washington+DC", "New+York+NY", "Seattle+WA", "Miami+FL"), 
                        destination = c("Los+Angeles+CA", "Austin+TX", "Chicago+IL", "Philadelphia+PA"), 
                        mode = "bicycling", 
                        departure = 1514742000)
results
# $Time
#              or Time.Los+Angeles+CA Time.Austin+TX Time.Chicago+IL Time.Philadelphia+PA
# 1 Washington+DC              856621         535146          247765                54430
# 2   New+York+NY              917486         596011          308630                32215
# 3    Seattle+WA              374692         678959          674989               956702
# 4      Miami+FL              829039         416667          452035               411283
# 
# $Distance
#              or Distance.Los+Angeles+CA Distance.Austin+TX Distance.Chicago+IL Distance.Philadelphia+PA
# 1 Washington+DC                 4567470            2838519             1303067                   266508
# 2   New+York+NY                 4855086            3126136             1590684                   160917
# 3    Seattle+WA                 1982354            3562970             3588297                  5051951
# 4      Miami+FL                 4559205            2279966             2381610                  2169382
# 
# $Status
#              or status.Los+Angeles+CA status.Austin+TX status.Chicago+IL status.Philadelphia+PA
# 1 Washington+DC                    OK               OK                OK                     OK
# 2   New+York+NY                    OK               OK                OK                     OK
# 3    Seattle+WA                    OK               OK                OK                     OK
# 4      Miami+FL                    OK               OK                OK                     OK

我需要計算一堆地址的行駛距離,所以我為它編寫了一個簡短的函數並將其放入同樣小的數據包中。 你可以在我的GitHub回購中找到它: https//github.com/JanMultmeier/GeoData/blob/master/GeoDataPackage/R/GetDist.R

這應該讓它運行:

require(devtools)
install_github("JanMultmeier/GeoData/GeoDataPackage")
library(GeoData)
getDist(from="1 Infinity Loop, Cupertino, CA 95014", to="1600 Amphitheatre Pkwy, Mountain View, CA 94043",modus="driving",get="distance")

它應該返回14.8公里。

Barryhunter已經暗示谷歌的使用限制,將此API的使用與在Google地圖上顯示結果聯系起來。

希望這仍然可以幫助一些偶然發現這篇文章的人(像我一樣)......

我已經使用Google Maps API編寫了googleway程序包

特別是, google_directions()函數將為您提供行車距離,路線,路線,腿,步等。而google_distance()函數將為您提供所有起點/目的地的距離矩陣

您需要Google API密鑰才能使用其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 <b>southeast</b> on <b>I-5 S</b>, 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"

鑒於google_directions()函數返回折線(當您搜索路線時在Google地圖上獲得的線),我們可以在Google地圖上繪制它

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

在此輸入圖像描述

在撰寫本文時, Renjin (一個基於Java的R解釋器)沒有很多軟件包來幫助解決這個問題。 這是一個不依賴於額外包的實現。

# 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 <value> element immediately follows the distance element.
    value = xml[ grep( "<distance>", 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 )
}

輸出:

distance( '44.5646', '-123.2620', '41.2861', '-124.0902' )
[1] 495892
distance( 44.5646, -123.2620, 41.2861, -124.0902, mode='walking' )
[1] 487715

從米到英尺的轉換是讀者的練習。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM