Exemple rapide de l’utilisation de leaflet dans un document de type “R notebook”
# Construction de la carte
library(leaflet)
# Export de la carte
library(htmlwidgets)
# Ouverture/préparation des données
library(rgdal)
## Loading required package: sp
## rgdal: version: 1.3-2, (SVN revision 755)
## Geospatial Data Abstraction Library extensions to R successfully loaded
## Loaded GDAL runtime: GDAL 2.2.1, released 2017/06/23
## Path to GDAL shared files: /usr/share/gdal/2.2
## GDAL binary built with GEOS: TRUE
## Loaded PROJ.4 runtime: Rel. 4.9.3, 15 August 2016, [PJ_VERSION: 493]
## Path to PROJ.4 shared files: (autodetected)
## Linking to sp version: 1.3-1
library(rgeos)
## rgeos version: 0.3-28, (SVN revision 572)
## GEOS runtime version: 3.5.1-CAPI-1.9.1 r4246
## Linking to sp version: 1.3-1
## Polygon checking: TRUE
# Ouverture d'une couche de polygones et création des centroides
data = readOGR('/home/mz/Bureau/data/cantons_bretagne.geojson')
## OGR data source with driver: GeoJSON
## Source: "/home/mz/Bureau/data/cantons_bretagne.geojson", layer: "cantons_bretagne"
## with 102 features
## It has 9 fields
data$centroids <- gCentroid(data, byid = TRUE)
## Label des cercles (ce qui apparait quand on click dessus)
data$label <- paste0("<b>", data$nom, "</b>",
"<br>Population du canton : ",
data$population, ' habitants')
## Initialisation de la carte leaflet
m <- leaflet(padding = 0)
m <- addProviderTiles(map = m,
provider = providers$Stamen.Watercolor)
## Ajout des cantons bretons
m <- addPolygons(map = m, data = data, opacity = 100,
color = "#FAFCFA",
weight = 0.25,
popup = data$label,
fill = T, fillColor = "pink",
fillOpacity = 75,
stroke = T)
## Centrage de la carte
m <- fitBounds(map = m,
lng1 = data@bbox[1],
lat1 = data@bbox[2],
lng2 = data@bbox[3],
lat2 = data@bbox[4])
Et voilà…
m