【问题标题】:How to get the longitude and latitude coordinates from a city name and country in R?如何从R中的城市名称和国家/地区获取经度和纬度坐标?
【发布时间】:2012-12-04 00:20:08
【问题描述】:

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

我的表名为test,结构如下:

Cityname  CountryCode
New York  US
Hamburg   DE
Amsterdam NL

【问题讨论】:

    标签: r maps openstreetmap rjsonio


    【解决方案1】:

    通过以下代码,我已经成功解决了这个问题。

    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),因此对于较大的数据集可能需要一段时间。但是,您可能只在将新城市添加到列表中时才会偶尔执行此操作。

    【讨论】:

    • 您也可以使用我的 geonames 包中的 GNsearch 执行此操作 - 它调用 geonames.org 网络服务,该服务与 OpenStreetMap 的 Nominatim 服务共享大量数据。
    • @Jochem 我该如何做相反的事情?我有纬度和经度,我需要像上面那样通过 json 格式使用开放街道查找城市和国家名称?
    【解决方案2】:

    为您提供一些其他选择。

    ggmap

    ggmaps 有一个函数geocode,它使用谷歌地图进行地理编码。这将您限制为每天 2,500 个。

    taRifx.geo

    taRifx.geo 的最新版本有一个 geocode 函数,它使用 Google 或 Bing 地图进行地理编码。 Bing 版本要求您使用(免费)Bing 帐户,但作为回报,您可以对更多条目进行地理编码。此版本的特点:

    • 服务选择(Bing 和 Google 地图都支持)
    • 登录支持(特别是对于 Bing,它需要帐户密钥,但作为交换,允许每天请求多一个数量级)
    • 一次对整个 data.frame 进行地理编码,包括一些节省时间的方法,例如忽略任何已进行地理编码的行
    • 强大的批量地理编码(这样任何错误都不会导致整个 data.frame 的地理编码价值丢失,适用于更大的工作)
    • 路线查找(从 A 点到 B 点的行程时间)

    【讨论】:

      【解决方案3】:

      试试这个我认为它会更好地解决这个问题

      > 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-17
        相关资源
        最近更新 更多