Solution : on créée d’abord une fonction qui convertit les dégrés minutes secondes en dégrés décimaux. On va exprimer ces angles en radians pour pouvoir les utiliser directement avec les fonctions trigonométriques de R :
<- function(vec) {
convert_degree # vec est un vecteur de taille 3 : c(deg, minute, second)
<- vec[1]
deg <- vec[2]
minute <- vec[3]
second stopifnot(minute < 60 & second < 60)
<- minute + second / 60
minute + minute / 60) * pi / 180
(deg }
Ensuite, on créée une fonction qui calcule la distance entre deux points :
<- function(coord_A, coord_B, R = 6378) {
dist_deg # convert
<- convert_degree(coord_A[[1]])
long_A <- convert_degree(coord_A[[2]])
lat_A <- convert_degree(coord_B[[1]])
long_B <- convert_degree(coord_B[[2]])
lat_B # distance
* acos(sin(lat_A) * sin(lat_B) + cos(lat_A) * cos(lat_B) * cos(long_A - long_B))
R }
Application :
dist_deg(list(c(2, 21, 7), c(48, 51, 24)),
list(c(1, 26, 3), c(43, 36, 16)))
## [1] 588.9053
En utilisant le package photon ou tidygeocoder:
<- c("compans cafarelli, toulouse", "INRAE, Auzeville")
my_address <- photon::geocode(my_address, limit = 1, key = "place")
locgeo.full ::geo(address = my_address, method = "osm",
tidygeocoderlat = latitude, long = longitude)
## # A tibble: 2 x 3
## address latitude longitude
## <chr> <dbl> <dbl>
## 1 compans cafarelli, toulouse 43.6 1.44
## 2 INRAE, Auzeville 43.5 1.50
library(leaflet)
<- leaflet() %>%
m addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng = locgeo.full$lon, lat = locgeo.full$lat, popup = "MT")
m
On montre ici le code utilisé.
Pour la France, on a utilisé le CRS officiel (EPSG:2154).
Pour la carte du monde, on a utilisé la projection de World Robinson. Pour d’autres représentations pour la surface globale de la terre, on pourra consulter cette page : https://mgimond.github.io/Spatial/coordinate-systems-in-r.html ainsi que des représentations originales sur : http://magrit.cnrs.fr/docs/projections_fr.html
Pour des représentations de l’Europe, cette page : https://observablehq.com/@toja/five-map-projections-for-europe
library(sf)
<- read_sf("Donnees/World WGS84/Pays_WGS84.shp")
world_sf <- world_sf[53, ]
fr <- st_transform(fr, 2154)
fr_2 <- par(mfrow=c(1,2))
op plot(st_geometry(fr), axes = T, main = "EPSG:4326")
plot(st_geometry(fr_2), axes = T, main = "EPSG:2154")
par(op)
title("Proposition 1", line = 3)
<- st_transform(world_sf, st_crs('ESRI:54030'))
world_az <- par(mfrow=c(2,1))
op plot(st_geometry(world_sf), axes = T, main = "EPSG:4326")
plot(st_geometry(world_az), axes = T, main = "ESRI:54030")
par(op)
title("Proposition 2", line = 3)
<- world_sf[c(8, 9,10,11,12,13,14, 15,16,17,18,19,20,22,24,25,26,
europe 27, 28, 31, 32, 33, 34, 35, 36, 37, 40, 41,43, 46, 47, 48, 49, 50,
52,53, 57, 56, 58, 59, 61, 64, 71, 74, 80, 85, 93),]
<- st_transform(europe, st_crs('ESRI:102031'))
europe_az <- par(mfrow=c(1, 2))
op plot(st_geometry(europe), axes = T, main = "EPSG:4326")
plot(st_geometry(europe_az), axes = T, main = "ESRI:102031")
par(op)
title("Proposition 3", line = 3)
Pour obtenir l’abcisse : \(10000+5\times 500 + \frac{1}{2}\times500=12750\) et pour l’ordonnée : \(15000+6\times 500=18000\)
library(readxl)
<- data.frame(read_excel("Donnees/population_mondiale/citypop.xls", skip = 16))
citypop <- data.frame(read_excel("Donnees/population_mondiale/cityevo.xls", skip = 16))
cityevo <- merge(x = citypop, y = cityevo[, c(4,9:24)], by = "City.Code") city
En utilisant la norme sf:
library(sf)
<- st_as_sf(city,
city_sf coords = c("Longitude","Latitude"),
crs = 4326) # On indique le systeme de coordonnées utilisé, ici WGS84
En utilisant la norme sp:
library(sp)
<- city
city_sp coordinates(city_sp) <- ~Longitude+Latitude
proj4string(city_sp) <- CRS(SRS_string = "EPSG:4326")
library(leaflet)
<- leaflet(city_sf) %>%
m addTiles() %>% # Add default OpenStreetMap map tiles
addCircles()
m
library(sf)
<- read_sf(dsn = "Donnees/velo toulouse/velo-toulouse.shp")
bike <- read_sf(dsn = "Donnees/velo toulouse/pop.shp") iris
st_crs(bike)
## Coordinate Reference System:
## User input: WGS 84
## wkt:
## GEOGCRS["WGS 84",
## DATUM["World Geodetic System 1984",
## ELLIPSOID["WGS 84",6378137,298.257223563,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["latitude",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["longitude",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",4326]]
st_crs(iris)
## Coordinate Reference System:
## User input: WGS 84
## wkt:
## GEOGCRS["WGS 84",
## DATUM["World Geodetic System 1984",
## ELLIPSOID["WGS 84",6378137,298.257223563,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["latitude",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["longitude",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",4326]]
library(raster)
<- raster("Donnees/pop_fr/fra_pd_2020_1km.tif") pop_fr
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
On utilise la syntaxe à la ggplot
library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.3 ✓ purrr 0.3.4
## ✓ tibble 3.1.0 ✓ dplyr 1.0.5
## ✓ tidyr 1.1.3 ✓ stringr 1.4.0
## ✓ readr 1.4.0 ✓ forcats 0.5.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x tidyr::extract() masks raster::extract()
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
## x dplyr::select() masks raster::select()
ggplot(iris, aes(geometry = geometry)) +
geom_sf()
On utilise la syntaxe classique :
plot(st_geometry(iris))
<- iris %>%
iris_tlse group_by(code_insee) %>%
summarise(p12_pop = sum(p12_pop))
## although coordinates are longitude/latitude, st_union assumes that they are planar
plot(st_geometry(iris_tlse))
iris_tlse
## Simple feature collection with 1 feature and 2 fields
## Geometry type: POLYGON
## Dimension: XY
## Bounding box: xmin: 1.350379 ymin: 43.53266 xmax: 1.515341 ymax: 43.66866
## Geodetic CRS: WGS 84
## # A tibble: 1 x 3
## code_insee p12_pop geometry
## <chr> <dbl> <POLYGON [°]>
## 1 31555 453317. ((1.366204 43.59024, 1.36626 43.59038, 1.365661 43.5908, 1…
plot(st_geometry(iris_tlse), lwd = 2)
plot(st_geometry(iris), add = T, lty = 2)
plot(st_geometry(bike), add = T, pch = 16, cex = 0.5, col = "royalblue")
Les jeux de données iris et bike sont exprimés dans le WGS 84.
st_crs(bike)
## Coordinate Reference System:
## User input: WGS 84
## wkt:
## GEOGCRS["WGS 84",
## DATUM["World Geodetic System 1984",
## ELLIPSOID["WGS 84",6378137,298.257223563,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["latitude",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["longitude",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",4326]]
st_crs(iris)
## Coordinate Reference System:
## User input: WGS 84
## wkt:
## GEOGCRS["WGS 84",
## DATUM["World Geodetic System 1984",
## ELLIPSOID["WGS 84",6378137,298.257223563,
## LENGTHUNIT["metre",1]]],
## PRIMEM["Greenwich",0,
## ANGLEUNIT["degree",0.0174532925199433]],
## CS[ellipsoidal,2],
## AXIS["latitude",north,
## ORDER[1],
## ANGLEUNIT["degree",0.0174532925199433]],
## AXIS["longitude",east,
## ORDER[2],
## ANGLEUNIT["degree",0.0174532925199433]],
## ID["EPSG",4326]]
On va les transformer dans le système officiel en France dont le EPSG vaut 2154
<- st_transform(bike, crs = 2154)
bike <- st_transform(iris, crs = 2154)
iris ggplot(data = iris, aes(geometry = geometry)) +
geom_sf() +
geom_sf(data = bike) +
ggtitle("Velo Toulouse")
plot(st_geometry(iris), axes = T)
plot(st_geometry(bike), add = T, pch = 16, col = "royalblue")
$area <- st_area(iris) iris
Dans la fonction st_intersection(), on positionne d’abord l’objet bike et ensuite l’objet iris :
<- st_intersection(bike, iris) bike
On trouve d’abord la localisation géographique du domicile et du lieu de travail :
<- c("2 impasse Armand Carrel, 31000 Toulouse, France",
address "1 Esplanade de l'université, 31000 Toulouse")
<- photon::geocode(address, limit = 1, key = "place")
locgeo.full locgeo.full
## location osm_id osm_type name
## 1 2 impasse Armand Carrel, 31000 Toulouse, France 2025525717 N <NA>
## 2 1 Esplanade de l'université, 31000 Toulouse 7216063191 N <NA>
## housenumber street postcode city state country
## 1 2 Impasse Armand Carrel 31200 Toulouse Occitanie France
## 2 1 Esplanade de l'Université 31000 Toulouse Occitanie France
## osm_key osm_value lon lat msg
## 1 place house 1.465337 43.63364 <NA>
## 2 place house 1.435015 43.60464 <NA>
Ensuite, on calcule le chemin optimal :
library(osrm)
## Data: (c) OpenStreetMap contributors, ODbL 1.0 - http://www.openstreetmap.org/copyright
## Routing: OSRM - http://project-osrm.org/
<- osrmRoute(
short_path src = locgeo.full[1, c("lon", "lat")],
dst = locgeo.full[2, c("lon", "lat")],
returnclass = "sp",
overview = "full"
)
On importe le fonds de carte :
<- SpatialPoints(locgeo.full[, c("lon", "lat")],
xy CRS("EPSG:4326"))
library(cartography)
## Warning in fun(libname, pkgname): rgeos: versions of GEOS runtime 3.9.0-CAPI-1.16.2
## and GEOS at installation 3.8.0-CAPI-1.13.1differ
<- getTiles(x = xy, type = "osm", zoom = 13) mtqOSM
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded ellps WGS 84 in Proj4 definition: +proj=merc +a=6378137
## +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null
## +wktext +no_defs +type=crs
## Warning in showSRID(uprojargs, format = "PROJ", multiline = "NO", prefer_proj =
## prefer_proj): Discarded datum World Geodetic System 1984 in Proj4 definition
On représente le trajet :
tilesLayer(mtqOSM)
title("Short path")
plot(xy, col = 2, cex = 2, add = TRUE)
plot(short_path, add = T, col = "royalblue", lwd = 2)
text(coordinates(xy), col = 2, pos = 3,
labels = c("My home", "My Work"))
La réponse a été inspirée de ce post : https://rcarto.github.io/Intro_a_la_carto_avec_R/ex/ville.html
On convertit les données sur les villes dans le CRS de Robinson :
<- st_transform(city_sf, "ESRI:54030") city_sf
On représente la carte avec les villes :
plot(st_geometry(world_az))
plot(st_geometry(city_sf), add = T, pch = 6, cex = 0.2)
par(mar = c(0,0,1.2,0), bg = "white")
plot(st_geometry(world_az), col = "lightblue", border = "white", lwd = 0.2, bg = "cornsilk2")
# ajout d'un ombrage pour les pays du monde
plot(st_geometry(world_az) + c(100000,-100000), add=T, col = "grey30", border = NA)
plot(st_geometry(world_az), col = "ivory4", border ="ivory3", lwd = 0.5, add=TRUE)
# choix des bornes de la discrétisation du taux de croissance
<- c(min(city_sf$X2015.2020), 0, 1, 2, 3, 4, max(city_sf$X2015.2020))
bks # choix des couleurs
<- carto.pal("wine.pal", 1, "green.pal", 5)
cols propSymbolsChoroLayer(x = city_sf, var = "X2020", border = "white", legend.title.cex = 0.6,
lwd = 0.5, symbols = "circle", inches = 0.2,
var2 = "X2015.2020", breaks = bks, col = cols,
legend.var.title.txt = "Population en 2020\n(en milliers)",
legend.var2.title.txt = "Taux de croissance\nannuel moyen\n(2015-2020)",
legend.var.pos = "topright",
legend.var2.pos = "topleft", legend.values.cex = 0.6)
layoutLayer(title = "Population des agglomérations urbaines en 2018",
sources = "WUP, 2018", author = "Inspiré de T. Giraud, 2017", col = "black",
coltitle = "white", scale = NULL, frame = FALSE, tabtitle = TRUE)