这是一种使用www.freegeoip.net 对IP 地址进行地理编码,并使用ggplot 制作地图的方法。
# some IP addresses - you have this already...
ips <- c(Louvre ="213.139.122.103",
British.Museum ="195.224.71.221",
Museo.del.Prado ="213.27.146.137",
Grand.Egyptian ="163.121.93.15",
Hermitage.Museum ="213.152.151.197",
MBNA ="200.218.240.120",
Sydney.Museum ="54.252.89.136",
MOMA ="63.117.124.131")
# you start here...
library(XML)
library(httr)
library(ggplot2)
get.geocode <- function(ip) { # returns lat/long given an ip address
url <- "http://www.freegeoip.net"
xml <- content(GET(url,path=paste("xml",ip,sep="/")),type="text/xml")
xpath <- c(lat="//Latitude",long="//Longitude")
sapply(xpath,function(xp) as.numeric(xmlValue(xml[xp][[1]])))
}
locs <- data.frame(t(sapply(ips,get.geocode)))
library(ggplot2)
ggplot(locs, aes(x=long,y=lat))+
borders("world", color="grey50", fill="grey90")+
geom_point(color="red", size=3)+
labs(x="",y="")+
theme_bw() + theme(axis.text=element_blank(),axis.ticks=element_blank())+
coord_fixed()
注意事项。 RDSTK 包是 Data Science Toolkit API 的包装器。虽然我喜欢这个想法,但我发现 DSK 有点古怪。除其他外,它不一定会找到每个合法的 IP 地址。例如,当我使用上面的数据集运行另一个答案时,它只找到 8 个 IP 中的 4 个。此外,他们使用 POST 一次获取多个结果的“批量”API 的工作方式不一定与它的 GET 接口(每个 http 请求获取一个结果)相同。见this post。
如果这是针对客户的,我会使用其中一种商业网络服务(例如MaxMind)来对 IP 地址进行地理编码并从中工作。只需 160 个 IP,您几乎不需要花费任何费用。
另外,borders(...) 使用 mapdata 包中的 worldHires 数据集,如您所见,这不是很好。我倾向于下载更好的数据集,例如world map on GADM。