使用ggmap绘制路线失败:route()获取坐标异常求助
Fix: ggmap Route Not Displaying & Coordinate Mismatch Issue
Problem Overview
I was trying to plot a route using ggmap, but the route wouldn’t show up on the map at all. When I checked the mainroute2 object, I noticed the longitude values were around 105—way off from the expected -75 range. I tried combinations of geom_path, geom_leg, ggmap, and qmap with no luck, even though this worked fine just last week.
Root Cause
The issue boiled down to incorrect coordinate formatting in the route() function:
- I was passing
fromandtoas vectors (c(lat, lon)) instead of a single concatenated string - I also tried using commas to separate coordinates, which doesn’t align with the function’s expected format
Corrected Code
The fix is straightforward: pass coordinates as a single string with latitude and longitude separated by a space. Here’s the working code:
# Correct format: single string with lat/lon separated by space mainroute2 <- route(from = "39.951 -75.173", to = "39.954 -75.195", alternatives = FALSE, structure = "route") map2 <- get_map( location = c(lon=-75.16662, lat=39.95258), source = "google", zoom = 13, maptype = "roadmap") ggmap(map2) + geom_path( aes(x = lon, y = lat ), alpha = 3/4, size = 1, color = "black", data = mainroute2 )
Key Takeaways
- The
route()function expectsfromandtoparameters to be single strings in the format"latitude longitude"—not vectors - Always use a space to separate latitude and longitude; using commas or other separators will cause the function to misparse coordinates, resulting in wildly incorrect locations (like the 105 longitude I encountered)
内容的提问来源于stack exchange,提问作者Ricardo Guerreiro
相关产品推荐
相关产品推荐

