|
|
@@ -0,0 +1,64 @@ |
|
|
|
library(sp) |
|
|
|
library(rgdal) |
|
|
|
library(stringr) |
|
|
|
library(tidyverse) |
|
|
|
library(jsonlite) |
|
|
|
library(maptools) |
|
|
|
library(geojsonio) |
|
|
|
|
|
|
|
# Lecture codes postaux <-> codes insee (! padding) |
|
|
|
# https://raw.githubusercontent.com/Rudloff/french-postal-codes-api/master/insee.csv |
|
|
|
read_csv2("insee.csv") %>% |
|
|
|
select(Codepos, insee = INSEE) %>% |
|
|
|
mutate(insee = insee %>% str_pad(5, "left", "0")) %>% |
|
|
|
distinct -> insee |
|
|
|
|
|
|
|
# Lecture carte et join avec codes postaux (! Corse) |
|
|
|
# http://osm13.openstreetmap.fr/~cquest/openfla/export/communes-20150101-100m-shp.zip |
|
|
|
readOGR("communes", "communes-20150101-100m") -> communes |
|
|
|
communes@data %>% |
|
|
|
mutate(insee = insee %>% str_replace("2(A|B)", "20")) %>% |
|
|
|
left_join(insee) -> communes@data |
|
|
|
|
|
|
|
rm(insee) |
|
|
|
|
|
|
|
# Écriture shapefile avec codes postaux |
|
|
|
communes <- communes[!is.na(communes$Codepos),] |
|
|
|
#writeOGR(communes, "communes_byCP", "communes_byCP", driver = "ESRI Shapefile") |
|
|
|
|
|
|
|
communes <- unionSpatialPolygons(communes, communes$Codepos) |
|
|
|
|
|
|
|
# Conversion geojson |
|
|
|
communes %>% geojson_list -> geojson |
|
|
|
|
|
|
|
geojson_write(geojson, file = "communes.json") |
|
|
|
|
|
|
|
# Ajout centroides |
|
|
|
geojson$features$geometry$coordinates %>% |
|
|
|
map(function(feature) |
|
|
|
{ |
|
|
|
if (!is.list(feature)) |
|
|
|
feature <- list(feature) |
|
|
|
|
|
|
|
feature %>% |
|
|
|
map(function(polygon) |
|
|
|
{ |
|
|
|
if(dim(polygon)[1] > 1) |
|
|
|
polygon %>% apply(2, mean) |
|
|
|
else |
|
|
|
polygon[1,,] %>% apply(2, mean) |
|
|
|
}) %>% |
|
|
|
{ |
|
|
|
c(map_dbl(.,1) %>% mean, |
|
|
|
map_dbl(.,2) %>% mean) |
|
|
|
} |
|
|
|
}) -> geojson$features$properties$centroids |
|
|
|
|
|
|
|
# Ajout id |
|
|
|
geojson$features$id <- geojson$features$properties$Codepos |
|
|
|
|
|
|
|
geojson$features <- lapply(geojson$features, function(feat) |
|
|
|
{ |
|
|
|
feat$id <- feat$properties$Codepos |
|
|
|
feat |
|
|
|
}) |