Skip to content

Instantly share code, notes, and snippets.

@datagistips
Last active September 8, 2021 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datagistips/3bea96f1e23ce81bf91e4effdfd56bb4 to your computer and use it in GitHub Desktop.
Save datagistips/3bea96f1e23ce81bf91e4effdfd56bb4 to your computer and use it in GitHub Desktop.
library(jsonlite)
library(glue)
library(leaflet)
library(magrittr)
library(htmltools)
# Teste si la chaîne est une référence cadastrale
isParcelle <- function(s) {
grepl("^([013-9]\\d|2[AB1-9])\\d{3}(0|[A-Z])[A-Z][0-9]{4}[a-z]?$", s)
}
# Retourne la parcelle et sa bbox
getParcelle <- function(ref_cad) {
code_insee <- substr(ref_cad, 1, 5)
section <- substr(ref_cad, 6, 7)
numero <- substr(ref_cad, 8, 11)
url <- glue("https://apicarto.ign.fr/api/cadastre/parcelle?code_insee={code_insee}&section={section}&numero={numero}&source_ign=PCI")
# Bbox
res <- jsonlite::fromJSON(url)
bb <- res$bbox
# Géométrie
coords <- res$features$geometry$coordinates[[1]]
x <- coords[,,,1]
y <- coords[,,,2]
coords <- cbind(x, y)
geometry <- st_polygon(list(coords)) %>% st_sfc %>% st_set_crs(4326)
list(geometry = geometry,
bb = bb,
code_insee = code_insee,
section = section,
numero = numero)
}
# Parcelle d'exemple
refParcelle <- "592200B0084"
# Est-ce une parcelle ?
if(isParcelle(refParcelle)) {
# Si oui, on la récupère
parcelle <- getParcelle(refParcelle)
}
# Affiche la carte
leaflet() %>%
addTiles() %>%
fitBounds(parcelle$bb[1], parcelle$bb[2], parcelle$bb[3], parcelle$bb[4]) %>%
addPolygons(data = parcelle$geometry,
label = HTML(glue("Code INSEE : {parcelle$code_insee}<br>Section : {parcelle$section}<br>Numéro : {parcelle$numero}")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment