从coordiantes中提取地址成分 [英] Extract address components from coordiantes

查看:87
本文介绍了从coordiantes中提取地址成分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用R反向地理编码.我首先使用了ggmap,但无法使其与我的API密钥配合使用.现在,我正在用googleway进行尝试.

I'm trying to reverse geocode with R. I first used ggmap but couldn't get it to work with my API key. Now I'm trying it with googleway.

newframe[,c("Front.lat","Front.long")]

  Front.lat Front.long
1 -37.82681   144.9592
2 -37.82681   145.9592

newframe$address <- apply(newframe, 1, function(x){
  google_reverse_geocode(location = as.numeric(c(x["Front.lat"], 
x["Front.long"])),
                         key = "xxxx")
})

这会将变量提取为列表,但我无法弄清楚结构.

This extracts the variables as a list but I can't figure out the structure.

我正在努力弄清楚如何将下面列出的地址部分提取为newframe中的变量

I'm struggling to figure out how to extract the address components listed below as variables in newframe

postal_codeadministrative_area_level_1administrative_area_level_2localityroutestreet_number

我希望每个地址部分都作为一个单独的变量.

I would prefer each address component as a separate variable.

推荐答案

将地址反向地理编码为newframe $ address之后,可以进一步提取地址分量,如下所示:

After reverse geocoding into newframe$address the address components could be extracted further as follows:

# Make a boolean array of the valid ("OK" status) responses (other statuses may be "NO_RESULTS", "REQUEST_DENIED" etc).
sel <- sapply(c(1: nrow(newframe)), function(x){
  newframe$address[[x]]$status == 'OK'
})

# Get the address_components of the first result (i.e. best match) returned per geocoded coordinate.
address.components <- sapply(c(1: nrow(newframe[sel,])), function(x){
  newframe$address[[x]]$results[1,]$address_components
})

# Get all possible component types.
all.types <- unique(unlist(sapply(c(1: length(address.components)), function(x){
  unlist(lapply(address.components[[x]]$types, function(l) l[[1]]))
})))

# Get "long_name" values of the address_components for each type present (the other option is "short_name").
all.values <- lapply(c(1: length(address.components)), function(x){
  types <- unlist(lapply(address.components[[x]]$types, function(l) l[[1]]))
  matches <- match(all.types, types)
  values <- address.components[[x]]$long_name[matches]
})

# Bind results into a dataframe.
all.values <- do.call("rbind", all.values)
all.values <- as.data.frame(all.values)
names(all.values) <- all.types

# Add columns and update original data frame.
newframe[, all.types] <- NA
newframe[sel,][, all.types] <- all.values

请注意,我只保留了每个组件的第一种类型,有效地跳过了政治"类型,因为它出现在多个组件中,并且可能是多余的,例如"administrative_area_level_1,政治".

Note that I've only kept the first type given per component, effectively skipping the "political" type as it appears in multiple components and is likely superfluous e.g. "administrative_area_level_1, political".

这篇关于从coordiantes中提取地址成分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆