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

JoF*_*wld 25 google-maps geocoding r

我已经尝试运行代码,通过谷歌地图对R中的位置进行地理编码,以及XML来自此博客文章的软件包: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)
}
Run Code Online (Sandbox Code Playgroud)

当我运行时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"
Run Code Online (Sandbox Code Playgroud)

如果我只是粘贴到浏览器中的API网址Philadelphia, PA附加到最后,就像传递给的字符串xmlParseTree一样,我下载时看到的结果看起来像合法的xml.

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

Ton*_*yal 23

您是否考虑过使用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))
  }
}
Run Code Online (Sandbox Code Playgroud)

以下是使用上述功能的方法:

x <- gGeoCode("Philadelphia, PA")
Run Code Online (Sandbox Code Playgroud)

这是你得到的结果.我想在原始代码中,lat和lng混在了一起?但希望这是你想要的:

> x
[1]  39.95233 -75.16379
Run Code Online (Sandbox Code Playgroud)

希望有助于小伙伴,

Tony Breyal


小智 5

此代码仅使用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]]))
Run Code Online (Sandbox Code Playgroud)