You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 from and to as 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 expects from and to parameters 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:24