Google maps 使用Google地图在R中进行地理编码

Google maps 使用Google地图在R中进行地理编码,google-maps,r,geocoding,Google Maps,R,Geocoding,我已经尝试通过Google Maps和本博文中的XML包运行代码到R中的地理编码位置: 以下是他的职能: getDocNodeVal=function(doc, path){ sapply(getNodeSet(doc, path), function(el) xmlValue(el)) } gGeoCode=function(str){ library(XML) u=paste('http://maps.google.com/maps/api/geocode/xml?senso

我已经尝试通过Google Maps和本博文中的
XML
包运行代码到R中的地理编码位置:

以下是他的职能:

getDocNodeVal=function(doc, path){
  sapply(getNodeSet(doc, path), function(el) xmlValue(el))
}

gGeoCode=function(str){
  library(XML)
  u=paste('http://maps.google.com/maps/api/geocode/xml?sensor=false&address=',str)
  doc = xmlTreeParse(u, useInternal=TRUE)
  str=gsub(' ','%20',str)
  lng=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lat")
  lat=getDocNodeVal(doc, "/GeocodeResponse/result/geometry/location/lng")
  c(lat,lng)
}
x <- gGeoCode("Philadelphia, PA")
运行
gGeoCode()
时,出现以下错误:

> gGeoCode("Philadelphia, PA")
failed to load external entity "http%3A//maps.google.com/maps/api/geocode/xml%3Fsensor=false&address=%20Philadelphia,%20PA"
Error: 1: failed to load external entity "http%3A//maps.google.com/maps/api/geocode/xml%3Fsensor=false&address=%20Philadelphia,%20PA"
如果我只是将API url粘贴到浏览器中,并在末尾附加
Philadelphia,PA
,就像传递给
xmlParseTree
的字符串一样,我会得到一个下载时看起来像合法xml的结果


这是代码的问题,还是我未能配置某些东西?

这是地理编码的另一个选项-可能更容易解析:


您考虑过使用json调用吗?看看您的代码,这样做也可以实现同样的效果(您需要从omegahat.com安装RCurl和RJSONIO包)

复制并粘贴到R:

library(RCurl)
library(RJSONIO)

construct.geocode.url <- function(address, return.call = "json", sensor = "false") {
  root <- "http://maps.google.com/maps/api/geocode/"
  u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
  return(URLencode(u))
}

gGeoCode <- function(address,verbose=FALSE) {
  if(verbose) cat(address,"\n")
  u <- construct.geocode.url(address)
  doc <- getURL(u)
  x <- fromJSON(doc,simplify = FALSE)
  if(x$status=="OK") {
    lat <- x$results[[1]]$geometry$location$lat
    lng <- x$results[[1]]$geometry$location$lng
    return(c(lat, lng))
  } else {
    return(c(NA,NA))
  }
}
希望这能帮助一个小伙伴


Tony Breyal

此代码仅使用XML库工作

library(XML)
url = 'http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true'
doc = xmlTreeParse(url, useInternal=TRUE)
lat = as.numeric(xmlValue(getNodeSet(doc, '//location/lat')[[1]]))
lng = as.numeric(xmlValue(getNodeSet(doc, '//location/lng')[[1]]))

我修改了Tony Breyal解决方案,以便
gGeoCode
函数也将地址向量作为输入。使用此版本,您不仅可以使用此返回值执行
gGeoCode(“宾夕法尼亚州费城”)
,还可以执行
gGeoCode(c(“宾夕法尼亚州费城”、“纽约州”)

  address            lat          lng          
1 "Philadelphia, PA" "39.952335"  "-75.163789" 
2 "New York, NY"     "40.7143528" "-74.0059731"
请注意,GoogleMapsAPI的每日限制为2500,因此向量不应该太长。以下是更新后的函数:

library(RCurl)
library(RJSONIO)

construct.geocode.url <- function(address, return.call = "json", sensor = "false") {
  root <- "http://maps.google.com/maps/api/geocode/"
  u <- paste(root, return.call, "?address=", address, "&sensor=", sensor, sep = "")
  return(URLencode(u))
}

gGeoCode <- function(address,verbose=FALSE) {
  require("plyr")
  if(verbose) cat(address,"\n")
  u <- aaply(address,1,construct.geocode.url)
  doc <- aaply(u,1,getURL)
  json <- alply(doc,1,fromJSON,simplify = FALSE)
  coord = laply(json,function(x) {
    if(x$status=="OK") {
      lat <- x$results[[1]]$geometry$location$lat
      lng <- x$results[[1]]$geometry$location$lng
      return(c(lat, lng))
    } else {
      return(c(NA,NA))
    }
  })
  if(length(address)>1) colnames(coord)=c("lat","lng")
  else names(coord)=c("lat","lng")
  return(data.frame(address,coord))
}
库(RCurl)
图书馆(RJSONIO)

construct.geocode.url我需要从
geocode
获取所有返回的地址,而不仅仅是第一个地址,因此我编写了一个小函数来实现这一点。它可用于地理编码反向地理编码

geocode <- function(address,reverse=FALSE)  {
  require("RJSONIO")
  baseURL <- "http://maps.google.com/maps/api/geocode/json?sensor=false&"

  # This is not necessary, 
  # because the parameter "address" accepts both formatted address and latlng

  conURL <- ifelse(reverse,paste0(baseURL,'latlng=',URLencode(address)),
                                  paste0(baseURL,'address=',URLencode(address)))  
  con <- url(conURL)  
  data.json <- fromJSON(paste(readLines(con), collapse=""))
  close(con) 
  status <- data.json["status"]
 if(toupper(status) == "OK"){
  t(sapply(data.json$results,function(x) {
      list(address=x$formatted_address,lat=x$geometry$location[1],
                                                 lng=x$geometry$location[2])}))
 } else { 
   warning(status)
   NULL 
 }
}
反向地理编码示例:

请注意,地址可以是格式化地址或latlng,不使用
reverse
参数,但它包含在其他地理编码服务中供将来使用

地理编码(“38.910262,-77.043565”)


这也可以通过我的软件包和有效的Google Maps API密钥来完成

library(googleway)

key <- "your_api_key"

df <- google_geocode("Philadelphia, PA",
                      key = key)

df$results$geometry$location
#        lat       lng
# 1 39.95258 -75.16522
library(googleway)

旁白键/主题外键:他可以使用str=URLencode(str)代替str=gsub(“”,'%20',str)。我在这里发表评论是因为我认为这是一个很酷的函数:)是的,一个非常酷的函数。要是能成功就好了!:-/json调用有效,请参见下面我的答案:)我知道这个问题很古老,但值得补充的是,现在包
ggmap
中有一个
geocode
函数,可以为您完成所有这些工作。@Tony Breyal:我在R 2.14.0上尝试了这段代码。不幸的是,我得到一个错误:
x$results[[1]]$geometry$location$lat:$运算符对原子向量无效
。我做错了什么?@radek返回的JSON代码从外观上看有点变化。我已经更新了代码,通过在fromJSON中添加simplify=FALSE来反映这一点。只要您有RJSONIO的最新版本,现在就应该可以工作了,因为simplify参数是在几个版本之前添加的。@TonyBreyal本着的精神,所以我编辑了您的答案以添加改进。如果您希望我将其还原并添加为单独的答案,我可以,但我可以这样做(并且您可以得到分数;-))。如果您想让我将
gGeoCode
添加到我的miscellany package
taRifx
中,以便更广泛地使用,我可以这样做。显然,你会被列为作者。@TonyBreyal我添加了一个版本,该版本还将地址向量作为输入。现在,我没有替换以前的版本,而是将我的版本放在文章的末尾。好的,我的修改版本也以地址向量作为输入,下面是一个回复。。。
     address                                                               lat      lng      
[1,] "Dupont Circle Northwest, Washington, DC 20036, USA"                  38.90914 -77.04366
[2,] "Dupont Circle, 1 Dupont Circle Northwest, Washington, DC 20036, USA" 38.90921 -77.04438
[3,] "Washington, DC 20036, USA"                                           38.90808 -77.04061
[4,] "Dupont Circle, Washington, DC 20036, USA"                            38.90958 -77.04344
     address                                                    lat      lng      
[1,] "40-58 Dupont Circle Northwest, Washington, DC 20036, USA" 38.91027 -77.04357
[2,] "Washington, DC 20036, USA"                                38.90808 -77.04061
[3,] "Dupont Circle, Washington, DC, USA"                       38.90969 -77.04334
[4,] "Northwest Washington, Washington, DC, USA"                38.94068 -77.06796
[5,] "District of Columbia, USA"                                38.90598 -77.03342
[6,] "Washington, DC, USA"                                      38.90723 -77.03646
[7,] "United States"                                            37.09024 -95.71289
library(googleway)

key <- "your_api_key"

df <- google_geocode("Philadelphia, PA",
                      key = key)

df$results$geometry$location
#        lat       lng
# 1 39.95258 -75.16522
df <- google_reverse_geocode(location = c(39.95258, -75.16522),
                             key = key)

df$results$formatted_address
# [1] "1414 PA-611, Philadelphia, PA 19102, USA"           "15th St Station - MFL, Philadelphia, PA 19102, USA"
# [3] "Center City West, Philadelphia, PA, USA"            "Center City, Philadelphia, PA, USA"                
# [5] "Philadelphia, PA, USA"                              "Philadelphia, PA 19107, USA"                       
# [7] "Philadelphia County, PA, USA"                       "Philadelphia-Camden-Wilmington, PA-NJ-DE-MD, USA"  
# [9] "Philadelphia Metropolitan Area, USA"                "Pennsylvania, USA"                                 
# [11] "United States"