Leaflet地图中实现起点到所有点最短距离连线方案问询
Hi there! Let's fix that polyline issue you're having. First, let's break down why your current code is producing those random-looking lines: the addPolylines() function in the R leaflet package connects points in the exact order they appear in your data frame—so right now it's linking the first to second, second to third, which isn't what you want.
Can this be done with just Leaflet?
Yes, but you'll need to pre-process your data first to create the correct line segments (start point ↔ each other location) before passing it to Leaflet. Leaflet is a visualization tool, so it relies on you providing the right data structure for the lines you want to draw.
Step-by-Step Fix
Define your start point
First, pick which location is your "starting point" (I'll use the first row in yourLocatiesdata frame as an example—adjust this if your start point is different):# Define your start point (change the index if needed) start_point <- Locaties[1, ]Create line segment data
We need to generate a new data frame where each pair of rows represents the start point and one of the other locations. This will give us the individual straight lines you're looking for:# Build data for lines: start point + each target point lines_data <- do.call(rbind, lapply(2:nrow(Locaties), function(i) { rbind(start_point, Locaties[i, ]) }))Update your Leaflet code
Now use thislines_datato draw the black lines from your start point to all other locations. I'll also clean up thelabelargument inaddCircleMarkers()(your original code had a syntax error there):leaflet(data = Locaties) %>% addProviderTiles(providers$Wikimedia) %>% addCircleMarkers( lng = ~lon, lat = ~lat, radius = 6, color = "red", label = ~Naam # Fixed syntax here ) %>% addPolylines( data = lines_data, lng = ~lon, lat = ~lat, opacity = 1, color = "black", weight = 4 )
What if you need road-based shortest paths?
If by "shortest distance" you mean the actual shortest route via roads (not straight lines), then Leaflet alone won't handle this. You'll need to use a package like osrm to calculate the route coordinates from your start point to each location, then pass those routes to Leaflet's addPolylines().
A quick note on your original code
You had a small syntax issue in addCircleMarkers(): label = paste("locatie" = Locaties$Naam) is incorrect. Using label = ~Naam is the proper way to map the Naam column to labels in leaflet.
内容的提问来源于stack exchange,提问作者Desmond Djoemena

