简体   繁体   English

从城市和州输入获取经度和纬度的快速方法

[英]Quick way to get longitude & latitude from City & State input

这可能是一个非常随机/晦涩的问题,但是其中是否包含一个包含将美国City State (例如“ CA”)输入转换为字符串并返回经度和纬度坐标的函数的包?

UPDATE 更新

Or you can do a devtools::install_github("hrbrmstr/localgeo") and run geocode from it (just built it). 或者,您可以执行一个devtools::install_github("hrbrmstr/localgeo")并从中运行geocode (只需构建它)。 It doesn't have rgdal , rgeos or httr dependencies, just dplyr . 它没有rgdalrgeoshttr依赖项,只有dplyr

Also this place has a free CSV file of ZIP/City/State/lon/lat you could just match or dplyr::left_join 另外, 这个地方有一个免费的CSV文件,您可以match ZIP或城市/州/ lon / lat或dplyr::left_join


No need to use an API: 无需使用API​​:

library(rgeos)
library(rgdal)
library(httr)
library(dplyr)

# httr's write_disk can act like a cache as it won't download if 
# the file exists

GET("http://www.mapcruzin.com/fcc-wireless-shapefiles/cities-towns.zip", 
    write_disk("cities.zip"))
unzip("cities.zip", exdir="cities")

# read in the shapefile
shp <- readOGR("cities/citiesx020.shp", "citiesx020")

# extract the city centroids with name and state

geo <- 
  gCentroid(shp, byid=TRUE) %>%
  data.frame() %>%
  rename(lon=x, lat=y) %>%
  mutate(city=shp@data$NAME, state=shp@data$STATE)

# lookup!

geo %>% filter(city=="Portland", state=="ME")

##         lon      lat     city state
## 1 -70.25404 43.66186 Portland    ME

geo %>% filter(city=="Berwick", state=="ME")

##         lon      lat    city state
## 1 -70.86323 43.26593 Berwick    ME

There may be more comprehensive shapefiles out there with these attributes. 具有这些属性的可能还有更全面的shapefile。 This one has 28,706 cities & towns, so it seems pretty comprehensive. 这个城市有28,706个城镇,因此似乎很全面。

Those can be easily wrapped into functions for easier use: 这些可以很容易地包装成函数以便于使用:

geo_init <- function() {

  try({
    GET("http://www.mapcruzin.com/fcc-wireless-shapefiles/cities-towns.zip",
        write_disk("cities.zip"))
    unzip("cities.zip", exdir="cities") })

  shp <- readOGR("cities/citiesx020.shp", "citiesx020")

  geo <-
    gCentroid(shp, byid=TRUE) %>%
    data.frame() %>%
    rename(lon=x, lat=y) %>%
    mutate(city=shp@data$NAME, state=shp@data$STATE)

}

geocode <- function(geo_db, city, state) {
  do.call(rbind.data.frame, mapply(function(x, y) {
    geo_db %>% filter(city==x, state==y)
  }, city, state, SIMPLIFY=FALSE))
}


geo_db <- geo_init()

geo_db %>% geocode("Portland", "ME")

##                lon      lat     city state
## Portland -70.25404 43.66186 Portland    ME

geo_db %>%
  geocode(c("Portland", "Berwick", "Alfred"), "ME")

##                lon      lat     city state
## Portland -70.25404 43.66186 Portland    ME
## Berwick  -70.86323 43.26593  Berwick    ME
## Alfred   -70.71754 43.47681   Alfred    ME

geo_db %>%
  geocode(city=c("Baltimore", "Pittsburgh", "Houston"),
          state=c("MD", "PA", "TX"))

##                  lon      lat       city state
## Baltimore  -76.61158 39.29076  Baltimore    MD
## Pittsburgh -79.99538 40.44091 Pittsburgh    PA
## Houston    -95.36400 29.76376    Houston    TX
https://maps.googleapis.com/maps/api/geocode/json?address={city},{state}

...of course replace {city} and {state} with the city/state you're searching for. ...当然可以将{city}和{state}替换为您要搜索的城市/州。 It returns a JSON string, so you can make this call via ajax and do JS processing. 它返回一个JSON字符串,因此您可以通过ajax进行此调用并执行JS处理。

Expanding @ZacWolf's answer, you can do this using my googleway package and the Google Maps API (for which you need an API key) 扩展@ZacWolf的答案,您可以使用我的googleway包和Google Maps API(为此需要API密钥)来完成此操作

library(googleway)

## your api key
key <- read.dcf("~/Documents/.googleAPI", fields = "GOOGLE_API_KEY")

google_geocode(address = "Los Angeles, California", key = key)

# $results

# address_components
# 1 Los Angeles, Los Angeles County, California, United States, Los Angeles, Los Angeles County, CA, US, locality, political, administrative_area_level_2, political, administrative_area_level_1, political, country, political
# formatted_address geometry.bounds.northeast.lat geometry.bounds.northeast.lng geometry.bounds.southwest.lat geometry.bounds.southwest.lng
# 1 Los Angeles, CA, USA                      34.33731                     -118.1553                      33.70369                     -118.6682
# geometry.location.lat geometry.location.lng geometry.location_type geometry.viewport.northeast.lat geometry.viewport.northeast.lng
# 1              34.05223             -118.2437            APPROXIMATE                        34.33731                       -118.1553
# geometry.viewport.southwest.lat geometry.viewport.southwest.lng                    place_id               types
# 1                        33.70369                       -118.6682 ChIJE9on3F3HwoAR9AhGJW_fL-I locality, political

And if you have multiple cities/states 如果您有多个城市/州

df <- data.frame(city = c("Portland", "Houston", "Pittsburg"),
                                 state = c("ME", "TX", "PA"))


res <- apply(df, 1, function(x) {
    google_geocode(address = paste0(x["city"], ", ", x["state"]), key = key)
})


lapply(res, function(x) x[['results']][['geometry']][['location']])

# [[1]]
# lat       lng
# 1 43.66147 -70.25533
# 
# [[2]]
# lat      lng
# 1 29.76043 -95.3698
# 
# [[3]]
# lat       lng
# 1 40.44062 -79.99589

ggmap::geocode wraps the Google and Data Science Toolkit geocoding APIs neatly: ggmap::geocode巧妙地包装了Google和Data Science Toolkit地理编码API:

df <- data.frame(city = c('Washington', 'Los Angeles'), 
                 state = c('DC', 'CA'))

df <- cbind(df, geocode(paste(df$city, df$state)))

df
##          city state        lon      lat
## 1  Washington    DC  -77.03687 38.90719
## 2 Los Angeles    CA -118.24368 34.05223

It also includes a mutate_geocode version, if you like dplyr grammar, though the full address has to be fully assembled as a column: 如果您喜欢dplyr语法,它还包括mutate_geocode版本,尽管完整地址必须完整地组装为一列:

library(dplyr)

df <- df %>% mutate(address = paste(city, state)) %>% mutate_geocode(address)

df
##          city state        address        lon      lat
## 1  Washington    DC  Washington DC  -77.03687 38.90719
## 2 Los Angeles    CA Los Angeles CA -118.24368 34.05223

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM