【R语言】利用高德地图批量处理银行网点地址获取经纬度和行政区

2021-01-28 11:24:08 浏览数 (1)

高德地图密钥Key的申请

01

查看后期视频:高德地图申请密钥key

密钥Key如何添加至RStudio?

代码语言:javascript复制
usethis::edit_r_environ()#打开environ界面
key="2ad35axxxxxxx"#定义完一定要保存
key <- Sys.getenv("key")

构建获取location的经纬度函数

代码语言:javascript复制
>library(xml2)
>library(rvest)
>library(dplyr)
>library(stringr)
>library(rjson)
>library(jsonlite)
>gGetLocation = function(address)  {
>key <- Sys.getenv("key")
>url =paste0("https://restapi.amap.com/v3/geocode/geo?key=",key,"&address=",address)
>data = read_html(url, encoding='utf-8') %>% html_text()
>df = as.data.frame(fromJSON(data))  
  return (df['geocodes.location']) 
}
# test,测试
> gGetLocation('南京市') 
     geocodes.location
1 118.796877,32.060255

构建获取district的区县函数

代码语言:javascript复制
gGetdistrictFuZhou = function(address)  {
  key <- Sys.getenv("lxl")
  url = paste0("https://restapi.amap.com/v3/geocode/geo?key=",key,"&city=","福州市","&address=",address)
  data = read_html(url, encoding='utf-8') %>% html_text()
  df = as.data.frame(fromJSON(data))  
  return (df['geocodes.district']) 
}
gGetdistrictFuZhou = function(address)  {
  key <- Sys.getenv("lxl")
  url = paste0("https://restapi.amap.com/v3/geocode/geo?key=",key,"&city=","福州市","&address=",address)
  data = read_html(url, encoding='utf-8') %>% html_text()
  df = as.data.frame(fromJSON(data))  
  return (df['geocodes.district']) 
}
#test 测试
>gGetdistrictFuZhou("凤城镇丹凤东路25号海联大厦1层")
  geocodes.district
1            连江县

批量处理

数据源结构特点:

图1 数据源结构

代码:

代码语言:javascript复制
library(readxl)
library(dplyr)
library(stringr)
library(tidyverse)
library(openxlsx)
YH <- read_excel("~/Desktop/YH.xlsx")
YH$经纬度 <- NA
YH$区县 <- NA
for(i in 1:nrow(YH)){
  print(i)
  if (is.na(YH$经纬度[i])) {
    try({YH$经纬度[i] <- gGetLocation(YH$address[i])})
  if(is.na(YH$区县[i])){
    try({YH$区县[i]<-gGetdistrictFuZhou(YH$address[i])})
  }
  }}
YH%>%separate(col=经纬度",into=c("lon","lat"),sep=",")->YH
write.xlsx(YH,"~/Desktop/微信公众号运营/银行网点.xlsx")

批量处理后数据结构:

图2 数据源结构

批量处理后的数据暂无缺失值,若存在个别缺失值很正常,通常是因为数据源地址结构不是省 市 区县 街道格式,若数据源地址结构无明显规律,建议url代码中添加“&city”,运行过程中有啥问题,请私聊我可改进代码~

0 人点赞