Skip to content

Instantly share code, notes, and snippets.

@cwickham
Forked from diegovalle/CreateRoutes.R
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save cwickham/1ea84d1db2226722bb0c to your computer and use it in GitHub Desktop.

Select an option

Save cwickham/1ea84d1db2226722bb0c to your computer and use it in GitHub Desktop.
library(stringr)
library(RCurl)
#Google polyline decoder borrowed from:
#http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/decode.js
DecodeLineR <- function(encoded) {
len = str_length(encoded)
encoded <- strsplit(encoded, NULL)[[1]]
index = 1
N <- 100000
df.index <- 1
array = matrix(nrow = N, ncol = 2)
lat = 0
dlat = 0
lng = 0
dlng = 0
b = 0
shift = 0
result = 0
while(index <= len) {
shift = 0
result = 0
repeat {
b = as.integer(charToRaw(encoded[index])) - 63
index <- index + 1
result = bitOr(result, bitShiftL(bitAnd(b, 0x1f), shift))
shift = shift + 5
if(b < 0x20) break
}
dlat = ifelse(bitAnd(result, 1),
-(result - (bitShiftR(result, 1))),
bitShiftR(result, 1))
lat = lat + dlat;
shift = 0
result = 0
b = 0
repeat {
b = as.integer(charToRaw(encoded[index])) - 63
index <- index + 1
result = bitOr(result, bitShiftL(bitAnd(b, 0x1f), shift))
shift = shift + 5
if(b < 0x20) break
}
dlng = ifelse(bitAnd(result, 1),
-(result - (bitShiftR(result, 1))),
bitShiftR(result, 1))
lng = lng + dlng
array[df.index,] <- c(lat = lat * 1e-05, lng = lng * 1e-5)
df.index <- df.index + 1
}
ret <- data.frame(array[1:df.index - 1,])
names(ret) <- c("lat", "lon")
return(ret)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment