Search code examples
rdictionaryroutescoordinatesggmap

Can't plot route with ggmap. route() does not retrieve correct coordinates?


I am trying to plot routes in ggmap, but they fail to appear on map. It seems to me that routes is getting the wrong coordinates. I tried both with geom_leg and geom_path. Here's the example:

mainroute2 <- route(from = c("39.951", "-75.173"),  # I tried with point and
               to = c("39.954","-75.195"),            # comma separator
               alternatives = FALSE, structure = "route")

 map2 <- get_map(
    location = c(lon=-75.16662, lat=39.95258), # painfully picked by hand
       source = "google", zoom = 13, maptype = "roadmap")


ggmap(map2) + geom_path(
       aes(x = lon, y = lat ),
       alpha = 3/4, size = 1, color = "black", data = mainroute2
      )

I've tried many alternatives and combinations of ggmap, qmap, geom_path, geom_leg. Everything fails. Last week I did it, but now I can't!

Additionaly, when you plot mainroute2 with ggplot (or if you inspect it visually), you see longitude coordinates of 105, which makes no sense since the route should be from "39,951", "-75,173" to "39,954","-75,195".

Please help!

Edit: Problem answered. The coordinates have to be a single collapsed char element, not a vector c(lat, lon). (I also edited my coordinates to point separator and not comma separator, which was also immediately pointed out)

Thank you


Solution

  • I can see 2 problems in your code.

    Prob#1: From/to argument of route function should be name or comma separated latitude and longitude.

    Prob#2: Use of , as decimal separator. May be that is not matching with locale settings of your system.

    The corrected code:

    library(ggmap)
    mainroute2 <- route(from = "39.951,-75.173",  # lat,lon
                        to = "39.954,-75.195",      
                        alternatives = FALSE, structure = "route")
    
    map2 <- get_map(
      location = c(lon=-75.16662, lat=39.95258), # painfully picked by hand
      source = "google", zoom = 13, maptype = "roadmap")
    
    # color is changed to Red to make it visible clearly 
    ggmap(map2) + geom_path(
      aes(x = lon, y = lat ),
      alpha = 3/4, size = 1.5, color = "red", data = mainroute2
    ) 
    

    enter image description here