Last active
October 18, 2017 18:37
-
-
Save AlienDeg/d6f82d37a3b353c065274c309679cd09 to your computer and use it in GitHub Desktop.
sightseeing optimization for people who like to walk
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(ggmap) | |
library(gtools) | |
library(dplyr) | |
library(ggplot2) | |
library(ggrepel) | |
what_to_see <- c('prague bus station', | |
"Pivo a parek, prague", | |
"Bar Na Palme, prague", | |
"Pivovar Hostivar,pragie", | |
"Pivni rozmanitost, prague", | |
"Minipivovar Beznoska, prague", | |
"Krkonosska hospudka, prague") | |
coordinates <-geocode(what_to_see) | |
coordinates <- cbind(what_to_see,coordinates) | |
map <-get_googlemap(center = c(lon = mean(coordinates$lon), lat = mean(coordinates$lat)), zoom = 12,size = c(640, 640),maptype = 'roadmap', color = 'bw' ) | |
ggmap(map) + | |
geom_point(aes(x = lon, y = lat), data = coordinates, colour = "blue", size = 2) + geom_text_repel(aes(x = lon, y = lat, label = what_to_see), data = coordinates, colour = ("black"), size = 2.8) | |
paths <- as.data.frame(permutations(n=length(what_to_see),r=length(what_to_see),v=what_to_see), stringsAsFactors = FALSE) | |
start <- what_to_see[1] | |
ways <- paths %>% filter(V1 == start) %>% as.data.frame( stringsAsFactors = FALSE) | |
ways$id <- paste0('path',1:nrow(ways)) | |
NcolsToReduce <- ncol(ways) - 2 | |
newWays <- lapply(1:NcolsToReduce, function(i){ | |
x <- select(ways, i, i+1, id) | |
names(x) <- c("from", "to", "id") | |
x | |
}) %>% bind_rows() %>% as.data.frame( stringsAsFactors = FALSE) | |
short_paths<- as.data.frame(combinations(length(what_to_see),2,v=what_to_see), stringsAsFactors = FALSE) | |
colnames(short_paths) <- c('from','to') | |
short1 <-mapdist(from = short_paths$from , to =short_paths$to, mode = "walking") | |
short2 <- short1 %>% select(to,from,everything()) | |
colnames(short2)[1:2] <- c('from','to') | |
short_allinfo <- rbind(short1,short2) | |
optimalPath <- inner_join(newWays,short_allinfo,by = (c('from'='from','to'='to'))) %>% group_by(id) %>% summarise(mins = sum(minutes),km = sum(km)) %>% ungroup() %>% filter(mins == min(mins)) %>% as.data.frame(stringsAsFactor = FALSE) | |
route_df <- newWays %>% filter(id == optimalPath[1,1]) | |
toPlot <- do.call(rbind,apply(route_df, 1, function(x) {route(x[1],x[2], structure = "route") })) | |
ggmap(map) + | |
geom_path( | |
aes(x = lon, y = lat), colour = "red", size = 1.5, | |
data = toPlot, lineend = "round" | |
)+ | |
geom_point(aes(x = lon, y = lat), data = coordinates, colour = "blue", size = 2) + geom_text_repel(aes(x = lon, y = lat, label = what_to_see), data = coordinates, colour = ("black"), size = 2.8) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment