Last active
August 14, 2017 05:50
-
-
Save ymattu/2a0cb5a32e83b5fc17b6caa76ec73679 to your computer and use it in GitHub Desktop.
緯度経度から逆ジオコーディング(ちょっと高速版)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
library(sf) | |
# 関数 | |
## 都道府県抽出 | |
#' @param sp_polygon object of class sf, sfc or sfg | |
#' @param lon longitude | |
#' @param lat latitude | |
find_pref <- function(sp_polygon, lon, lat) { | |
which.row <- suppressMessages(sf::st_contains(sp_polygon, sf::st_point(c(lon, lat)), sparse = FALSE)) %>% | |
grep(TRUE, .) | |
if (identical(which.row, integer(0)) == TRUE) { | |
return(NA) | |
} else { | |
geos <- sp_polygon[which.row, ] %>% | |
dplyr::mutate_if(is.factor, as.character) | |
place_name = geos$KEN %>% | |
stringr::str_replace_all("NA", "") | |
return(place_name) | |
} | |
} | |
## 住所(何丁目レベル)判定 | |
#' @param sp_polygon object of class sf, sfc or sfg | |
#' @param pref prefecture | |
#' @param lon longitude | |
#' @param lat latitude | |
find_place <- function(sp_polygon, pref, lon, lat) { | |
if(is.na(pref) == TRUE) { | |
return(NA) | |
} | |
sp_pref <- sp_polygon %>% | |
dplyr::mutate_if(is.factor, as.character) %>% | |
filter(KEN_NAME == pref) | |
which.row <- suppressMessages(sf::st_contains(sp_pref, sf::st_point(c(lon, lat)), sparse = FALSE)) %>% | |
grep(TRUE, .) | |
if (identical(which.row, integer(0)) == TRUE) { | |
return(NA) | |
} else { | |
geos <- sp_pref[which.row, ] | |
place_name = paste(geos$GST_NAME, | |
geos$CSS_NAME, | |
geos$MOJI, | |
sep = ",") %>% | |
stringr::str_replace_all("NA", "") | |
return(place_name) | |
} | |
} | |
## 県と市区町村、番地を検索 | |
##' @param sp1 市区町村境界shapefile | |
##' @param sp2 番地レベルshapefile | |
##' @param longitude 経度 | |
##' @param latitude 緯度 | |
find_pref_place <- function(sp1, sp2, longitude, latitude) { | |
pref <- find_pref(sp1, longitude, latitude) | |
if(is.na(pref) == TRUE) { | |
return(NA) | |
} | |
city_banchi <- find_place(sp2, pref, longitude, latitude) | |
return(paste(pref, city_banchi, sep = ",")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment