gpt4 book ai didi

r - 如何从R中的城市名称和国家获得经纬度坐标?

转载 作者:行者123 更新时间:2023-12-04 01:26:51 26 4
gpt4 key购买 nike

我有一长串城市名称和国家/地区,我想将它们绘制在 map 上。为了做到这一点,我需要每个城市的经度和纬度信息。

我的 table 叫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),因此较大的数据集可能需要一段时间。但是,当新城市添加到列表中时,您可能只偶尔这样做一次。

关于r - 如何从R中的城市名称和国家获得经纬度坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13905098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com