library(dplyr)
library(jsonlite)
library(leaflet)
library(htmlwidgets)
library(htmltools)
Import gpx track and convert to geojson
source("R/tidy_gpx.R")
## import gpx track
track <- tidy_gpx("data/Move_2017_07_12_11_47_34_Cycling.gpx")
track
## # A tibble: 476 x 4
## lat lon ele time
## <dbl> <dbl> <dbl> <dttm>
## 1 60.53521 8.207308 799.0000 2017-07-12 08:47:34
## 2 60.53521 8.207295 799.0000 2017-07-12 08:47:39
## 3 60.53524 8.207430 798.9797 2017-07-12 08:48:38
## 4 60.53528 8.207570 798.6788 2017-07-12 08:48:41
## 5 60.53534 8.208882 794.3352 2017-07-12 08:49:41
## 6 60.53408 8.205974 794.0000 2017-07-12 08:50:41
## 7 60.53406 8.205976 793.9864 2017-07-12 08:50:47
## 8 60.53397 8.206029 792.9795 2017-07-12 08:51:04
## 9 60.53324 8.204063 791.0000 2017-07-12 08:51:42
## 10 60.53199 8.199522 784.0000 2017-07-12 08:52:42
## # ... with 466 more rows
## reorder columns
track <- track %>% select(lon, lat, ele)
## bounding box coordinates
bb <- track %>% summarise_at(vars(lon, lat), funs(min, max))
bb
## # A tibble: 1 x 4
## lon_min lat_min lon_max lat_max
## <dbl> <dbl> <dbl> <dbl>
## 1 7.21273 60.49316 8.208882 60.69084
## Convert to json
track <- toJSON(track, dataframe = "values")
geojson <- sprintf('{"type":"Feature","geometry":{"type":"LineString","coordinates":%s},"properties":null}', track)
## unbox magic
geojson <- toJSON(fromJSON(geojson), auto_unbox = TRUE)
# Check if correct geojson objects
geojsonlint::geojson_lint(geojson)
## [1] TRUE
Javascript dependencies
elevationPlugin <- htmlDependency("Leaflet.elevation", "0.0.4",
src = "js/elevation/",
script = "leaflet.elevation-0.0.4.src.js",
stylesheet = "leaflet.elevation-0.0.4.css")
d3Plugin <- htmlDependency("d3", "3.5.17",
src = "js/d3/",
script = "d3.js")
registerPlugin <- function(map, plugin) {
map$dependencies <- c(map$dependencies, list(plugin))
map
}
Leaflet map
leaflet() %>%
fitBounds(bb$lon_min, bb$lat_min, bb$lon_max, bb$lat_max) %>%
addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
# Register plugins on this map instance
registerPlugin(d3Plugin) %>%
registerPlugin(elevationPlugin) %>%
# Add JS, `this` refers to the Leaflet map.
onRender('function(el, x, data) {
var elev = L.control.elevation({width: 300});
elev.addTo(this);
L.geoJson(data, {
onEachFeature: elev.addData.bind(elev)}).addTo(this);
}', data = geojson)