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

前端 未结 5 593
失恋的感觉
失恋的感觉 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:05

    You need RCurl or an equivalent here.

    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')
    

    Result:

    [1] 17224.41
    

提交回复
热议问题