我尝试通过 Google map 和此博文中的 XML
包运行代码来对 R 中的位置进行地理编码:
http://www.r-chart.com/2010/07/maps-geocoding-and-r-user-conference.html
以下是他的职能:
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)
}
当我运行 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))
}
}
以下是如何使用上述功能:
x <- gGeoCode("Philadelphia, PA")
这就是你得到的结果。我认为在原始代码中,lat 和 lng 混淆了?但希望这就是您想要的:
> x
[1] 39.95233 -75.16379
希望对小伙伴有帮助
托尼·布雷亚尔
关于google-maps - 使用 Google map 在 R 中进行地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3257441/