我有一个长长的城市和国家名称列表,我想在地图上标出它们。为此,我需要每个城市的经纬度信息。
我的表格名为test
,具有以下结构:
Cityname CountryCode
New York US
Hamburg DE
Amsterdam NL
我有一个长长的城市和国家名称列表,我想在地图上标出它们。为此,我需要每个城市的经纬度信息。
我的表格名为test
,具有以下结构:
Cityname CountryCode
New York US
Hamburg DE
Amsterdam NL
使用以下代码,我已成功解决了这个问题。
library(RJSONIO)
nrow <- nrow(test)
counter <- 1
test$lon[counter] <- 0
test$lat[counter] <- 0
while (counter <= nrow){
CityName <- gsub(' ','%20',test$CityLong[counter]) #remove space for URLs
CountryCode <- test$Country[counter]
url <- paste(
"http://nominatim.openstreetmap.org/search?city="
, CityName
, "&countrycodes="
, CountryCode
, "&limit=9&format=json"
, sep="")
x <- fromJSON(url)
if(is.vector(x)){
test$lon[counter] <- x[[1]]$lon
test$lat[counter] <- x[[1]]$lat
}
counter <- counter + 1
}
由于这里调用了一个外部服务(openstreetmaps.org),对于较大的数据集可能需要一些时间。不过,你很可能只在列表中添加新城市时偶尔这样做。
这里还有一些其他的选项供您选择。
ggmaps
ggmaps有一个名为geocode
的函数,它使用Google Maps进行地理编码。这使您每天只能编码2,500个地址。
taRifx.geo
最新版本的taRifx.geo有一个名为geocode
的函数,它可以使用Google或Bing地图进行地理编码。Bing版本需要您使用(免费)的Bing账户,但换取更多的地址编码次数。此版本具有以下功能:
尝试这个,我认为这将是解决这个问题的更好方法。
> library(ggmap)
Loading required package: ggplot2
Google Maps API Terms of Service: http://developers.google.com/maps/terms.
Please cite ggmap if you use it: see citation('ggmap') for details.
#Now you can give city name or country name individually
> geocode("hamburg")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=hamburg&sensor=false
lon lat
1 9.993682 53.55108
geocode("amsterdam")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=amsterdam&sensor=false
lon lat
1 4.895168 52.37022
> geocode("new york")
Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=new+york&sensor=false
lon lat
1 -74.00594 40.71278