Skip to content

Instantly share code, notes, and snippets.

@Valexandre
Last active December 5, 2023 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Valexandre/1fee25eeb4144061a1a036c8caed0810 to your computer and use it in GitHub Desktop.
Save Valexandre/1fee25eeb4144061a1a036c8caed0810 to your computer and use it in GitHub Desktop.
Comment créer un plan d'agglomération avec les temps de parcours à vélo ?
library(tidyverse)
library(readr)
library(sf)
library(ggmap)
library(osmdata)
library(ggforce)
APIGG<-"XXXXX"
register_google(key = APIGG)
# Fonctions utiles
st_x = function(x) st_coordinates(x)[,2]
st_y = function(x) st_coordinates(x)[,1]
`%!in%` = function(x,y) !(x %in% y)
# On va chercher la bonne zone dans OverPassTurbo
# This has been generated by the overpass-turbo wizard.
# The original search was:
# “"mairie, hôtel de ville"”
# */
# [out:json][timeout:25];
# // gather results
# (
# // query part for: “"mairie, hôtel de ville"”
# node["amenity"="townhall"]({{bbox}});
# way["amenity"="townhall"]({{bbox}});
# relation["amenity"="townhall"]({{bbox}});
# );
# // print results
# out body;
# >;
# out skel qt;
# Et on exporte le fichier en geojson
Lieux<-st_read("export.geojson")
# Pour la carte, on importe fleuves, autoroutes, nationales et départementales.
osm_rivers.sf <- opq(bbox = st_bbox(Lieux)) %>%add_osm_feature(key = 'waterway', value = 'river') %>%osmdata_sf()
osm_rivers.sf <- osm_rivers.sf$osm_lines
osm_roads_primary.sf <-
opq(bbox = st_bbox(Lieux)) %>%
add_osm_feature(key = 'highway', value = 'trunk') %>%
osmdata_sf()
osm_roads_primary.sf <- osm_roads_primary.sf$osm_lines
osm_roads_secondary.sf <-
opq(bbox = st_bbox(Lieux)) %>%
add_osm_feature(key = 'highway', value = 'secondary') %>%
osmdata_sf()
osm_roads_secondary.sf <- osm_roads_secondary.sf$osm_lines
osm_roads_tertiary.sf <-
opq(bbox = st_bbox(Lieux)) %>%
add_osm_feature(key = 'highway', value = 'tertiary') %>%
osmdata_sf()
osm_roads_tertiary.sf <- osm_roads_tertiary.sf$osm_lines
#On récupère les centroides des mairies pour n'en garder qu'un point.
Lieux<-Lieux%>%mutate(centre=st_centroid(geometry),
latitude=st_x(centre),
longitude=st_y(centre))
#On veut filtrer les points les plus proches pour éviter de calculer des distances trop lointaines.
Lieux2<-Lieux
Lieux2<-st_transform(Lieux2,crs=2154)
Lieux<-st_transform(Lieux,crs=2154)
what<-st_is_within_distance(Lieux,Lieux2,dist=3500)
what<-as.data.frame(what)
what$LatDepart<-Lieux$latitude[what$row.id]
what$LongDepart<-Lieux$longitude[what$row.id]
what$LatArrivee<-Lieux$latitude[what$col.id]
what$LongArrivee<-Lieux$longitude[what$col.id]
what$idDep<-Lieux$id[what$row.id]
what$idArr<-Lieux$id[what$col.id]
what<-what%>%filter(row.id!=col.id)
what<-what%>%rowwise()%>%mutate(min=min(c(row.id,col.id)),
max=max(c(row.id,col.id)))
what2<-what[!duplicated(what[,9:10]),]
# On lance le géocode
for (i in 1:nrow(what2)){
GOOGLECYCLING<-route(from=revgeocode(c(lon = what2$LongDepart[i], lat = what2$LatDepart[i])),
to=revgeocode(c(lon = what2$LongArrivee[i], lat = what2$LatArrivee[i])), mode = "bicycling",
structure = "route", output = "simple",
alternatives = FALSE, messaging = FALSE, sensor = FALSE,
override_limit = FALSE)
what2$MinutesVelo[i]<-sum(GOOGLECYCLING$minutes,na.rm=T)
}
what2$TempsDiscret<-ifelse(what2$MinutesVelo<5,"1. <5 min.",
ifelse(what2$MinutesVelo>=5 & what2$MinutesVelo<10,"2. Entre 5 et 10 min.",
ifelse(what2$MinutesVelo>=10 & what2$MinutesVelo<15,"3. Entre 10 et 15 min.","4.Plus de 15 min.")))
#On ne garde que les 5 plus proches
what2Small<-top_n(what2%>%ungroup()%>%group_by(idDep)%>%mutate(rangtemps=rank(-MinutesVelo)),5,wt=-MinutesVelo)
# On enlève les mairies annexes et les mairies de quartier
LieuxAnnexe<-Lieux%>%filter(grepl("nnexe",name))%>%select(id)
Quartiers<-Lieux%>%filter(grepl("quartier",name))%>%select(id)
what2Small<-what2Small%>%filter(idDep%!in%LieuxAnnexe$id)%>%filter(idArr %!in%LieuxAnnexe$id)
what2Small<-what2Small%>%filter(idDep%!in%Quartiers$id)%>%filter(idArr %!in%Quartiers$id)
deps<-st_read("https://raw.githubusercontent.com/gregoiredavid/france-geojson/master/departements.geojson")
jpeg(filename = "PlanDeVilleAVelo.jpg", width=4000, height = 2200, quality=100, units = "px",type="cairo")
ggplot()+
geom_sf(data = osm_rivers.sf, colour = '#7dcea2', size = 1) +
geom_sf(data = osm_roads_primary.sf, colour = '#636363', size = 0.1,alpha=0.7) +
geom_sf(data = osm_roads_secondary.sf, colour = '#636363', size = 0.05,alpha=0.5) +
geom_sf(data = osm_roads_tertiary.sf, colour = '#636363', size = 0.02,alpha=0.3) +
geom_sf(data=deps,colour="black",fill=NA)+
geom_link(data=what2Small, aes(x = LongDepart, y = LatDepart,
xend = LongArrivee, yend = LatArrivee, colour = TempsDiscret),
size=1.2,alpha=0.7)+
geom_point(data=st_set_geometry(Lieux,NULL),aes(longitude,latitude),colour="black")+
ggrepel::geom_label_repel(data=st_set_geometry(Lieux,NULL)%>%filter(!is.na(name))%>%
filter(!(grepl("nnexe",name))),
aes(longitude,latitude,label=name),colour="black")+
scale_colour_manual("Temps de parcours", values=c("#1EA0E6", "#f4b538", "#CC2828","#991e1e"))+
coord_sf(xlim = c(st_bbox(Lieux%>%st_transform(crs=4326))['xmin'], st_bbox(Lieux%>%st_transform(crs=4326))['xmax']),
ylim = c(st_bbox(Lieux%>%st_transform(crs=4326))['ymin'], st_bbox(Lieux%>%st_transform(crs=4326))['ymax']), datum=NA) +
theme_void()+
labs(title=" Combien de temps mettrait-on en vélo à relier les mairies de région XXX ?",
caption= " Carte : Victor Alexandre. Données OpenStreetMap & GoogleMaps ")+
theme(legend.position = "top", axis.title.x = element_blank(),
axis.title.y = element_blank(),text=element_text(size=40,family="Bahnschrift"))+
NULL
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment