Skip to content

Instantly share code, notes, and snippets.

@datagistips
Last active September 8, 2021 11:45

Revisions

  1. datagistips revised this gist Sep 8, 2021. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions getParcelle.R
    Original file line number Diff line number Diff line change
    @@ -2,6 +2,7 @@ library(jsonlite)
    library(glue)
    library(leaflet)
    library(magrittr)
    library(htmltools)

    # Teste si la chaîne est une référence cadastrale
    isParcelle <- function(s) {
  2. datagistips revised this gist Sep 7, 2021. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions getParcelle.R
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,7 @@
    library(jsonlite)
    library(glue)
    library(leaflet)
    library(magrittr)

    # Teste si la chaîne est une référence cadastrale
    isParcelle <- function(s) {
  3. datagistips created this gist Sep 7, 2021.
    50 changes: 50 additions & 0 deletions getParcelle.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    library(jsonlite)
    library(glue)
    library(leaflet)

    # 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}")))