从这个问题中我不清楚你到底想从谷歌那里得到什么。我猜是纬度和经度。如果是,请尝试屏幕截图后面的代码。编辑:根据 Ari B. Friedman 的评论,修改为包括使用包中的geocode
函数的替代(和更简单)方法。ggmap
# Read in the text from your example
mydf <- read.csv(con <- textConnection(
"streetnumber|street|city|state
1150|FM 1960 West Road|Houston|TX
701|Keller Parkway|Keller|TX"), header = TRUE, sep = "|", check.names = FALSE)
# APPROACH 1 - works but Approach 2 probably better (see below)
# Create a new column for the URL to pass to Google API
mydf$url <- with(mydf, paste("http://maps.googleapis.com/maps/api/geocode/xml?address=",
streetnumber,
gsub(" ", "+", street),
city, "+",
state, "+",
"&sensor=false",
sep = ""))
# Check to see what we have in the data frame
str(mydf)
library(XML)
latlon <- lapply(mydf$url, function(x) { # process each element in the column 'url'
myxml <- xmlTreeParse(x, useInternal = TRUE) # pass the element (an URL) to the XML function
# parse the result
lat = xpathApply(myxml, '/GeocodeResponse/result/geometry/location/lat', xmlValue)[[1]]
lon = xpathApply(myxml, '/GeocodeResponse/result/geometry/location/lng', xmlValue)[[1]]
data.frame(lat = lat, lon = lon) # return the latitude and longitude as a data frame
})
# We end up with a list of data frames, so merge the data frames into one:
library(reshape)
latlon <- merge_all(latlon)
# Then bolt the columns on to your existing data frame
mydf <- cbind(mydf, latlon, stringsAsFactors = FALSE)
# We want the latitude and longitude to numbers, not characters
mydf$lat <- as.numeric(mydf$lat)
mydf$lon <- as.numeric(mydf$lon)
require(ggmap)
# APPROACH 2 - let ggmap do the heavy lifting (and
# comment out Approach 1 if you use this)
mydf$location <- with(mydf, paste(streetnumber,street, city, state,sep = ", "))
latlon <- geocode(mydf$location)
mydf <- cbind(mydf, latlon, stringsAsFactors = FALSE)
# Now plot.
# Be careful when specifying the zoom argument, because larger values can cause
# points to be dropped by geom_point()
ggmap(get_googlemap(maptype = 'roadmap', zoom = 6, scale = 2), extent = 'panel') +
geom_point(data = mydf, aes(x = lon, y = lat), fill = "red", colour = "black",
size = 3, shape = 21)