I am working on program connected to Traveling Salesman Problem. I use R and I load data where is lon,lng and calculate distances using osrm package. Like this:
distance_matrix <- matrix(NA, nrow = nrow(data), ncol = nrow(data))
for (i in 1:nrow(data)) {
for (j in i:nrow(data)) {
if (i != j) {
route <- osrmRoute(c(data[i,]$lng,data[i,]$lat),c(data[j,]$lng,data[j,]$lat))
distance_matrix[i,j] <- route$distance
distance_matrix[j,i] <- route$distance
}
}
}
My question is- Is there any way after I calculate the TSP how to show final route connecting already calculated routes(and how to save them)?
I know how to show one route like this:
leaflet(route) |>
addTiles() |>
addPolylines(label = ~ sprintf("%d min - %d km", round(duration), round(distance)),
labelOptions = labelOptions(noHide = FALSE))
but this show only one route and I would love to show after using the TSP algorithm the final smallest route(using already calculated one).
Thank u
If your aim is just to use a distance matrix and test out different TSP approaches, I'd guess it's fine to grab that matrix from
osrm::osrmTable(), solve your task (assuming your solvers are returning a sequence of point names or indices, i.e. row numbers of distance matrix) and get a route fromosrm::osrmRoute()for a location sequence. With some example data fromosrmandTSPpackage it might look something like this:If you need individual segments, it would still make sense to request only routes that are part of TSP results, perhaps something like this:
If it would not work for you, please add more details regarding your constraints and scope of your work.
Depends on the actual problem and topic, but for thesis, I would have assumed that http://project-osrm.org/ or any other remotely hosted routing service is not an option and you'd need to host your own osrm for experiments and/or work with OpenStreetMap data and network analysis tools (i.e.
igraph,sfnetworks).