Skip to content

Instantly share code, notes, and snippets.

@tim-salabim
Created January 11, 2020 10:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim-salabim/a9740baae9ab879b0c79893132d959a3 to your computer and use it in GitHub Desktop.
Save tim-salabim/a9740baae9ab879b0c79893132d959a3 to your computer and use it in GitHub Desktop.
library(V8)
library(mapview)
library(geojsonsf)
ct = v8(global="window")
ct$source("https://cdn.jsdelivr.net/npm/flatgeobuf@2.0.1/dist/flatgeobuf-geojson.min.js")
ct$get("Object.keys(window)")
fran = sf_geojson(franconia[1, ])
jsfun = V8::JS(
"(function(x) {
flatgeobuf.serialize(JSON.parse(x));
})"
)
ct$assign("serialize", jsfun)
ct$assign("fran", fran)
ct$assign("out", V8::JS("serialize(fran)"))
@jeroen
Copy link

jeroen commented Jan 11, 2020

Make sure you use the latest V8 which has better object buffer handling! Also you need a polyfill as described here. This works for me:

library(V8)
library(mapview)
library(geojsonsf)

ct = v8(global="window")
ct$source("https://cdn.jsdelivr.net/npm/flatgeobuf@2.0.1/dist/flatgeobuf-geojson.min.js")
ct$source("https://cdn.jsdelivr.net/npm/text-encoding@0.6.4/lib/encoding.min.js")

fran = sf_geojson(franconia[1, ])
ct$call('flatgeobuf.serialize', JS(fran))

@tim-salabim
Copy link
Author

Thanks so much @jeroen!!

This now works nicely and enables me to test things a lot more flexibly.

library(V8)
library(mapview)
library(geojsonsf)
library(leaflet)
# remotes::install_github("r-spatial/leafem")
library(leafem)

writeFgb = function(x) {
  x = geojsonsf::sf_geojson(x)
  
  ct = V8::v8(global="window")
  ct$source("https://cdn.jsdelivr.net/npm/flatgeobuf@2.0.1/dist/flatgeobuf-geojson.min.js")
  ct$source("https://cdn.jsdelivr.net/npm/text-encoding@0.6.4/lib/encoding.min.js")
  
  bin = ct$call('flatgeobuf.serialize', V8::JS(x))

  fl = tempfile(fileext = ".fgb")
  writeBin(bin, fl)
  
  return(invisible(fl))
  
}


n = 1e4

df1 = data.frame(id = 1:n,
                 id2 = n:1,
                 x = runif(n, -5, 20),
                 y = runif(n, 40, 55))
df1 = df1[order(c(df1$x)), ]

pts = sf::st_as_sf(df1, coords = c("x", "y"), crs = 4326)
# pts$pop = leafpop::popupTable(pts)

fl = writeFgb(pts)

leaflet(
  options = 
    leafletOptions(
      preferCanvas = TRUE
      , crs = leafletCRS(
        crsClass = "L.CRS.EPSG3857"
      )
    )
) %>%
  addTiles() %>%
  leafem:::addFgb(
    fl
    , gl = FALSE
    , group = "counties"
    , label = "id"
    , popup = TRUE
    , fillColor = "blue"
    , fillOpacity = 0.6
    , color = "black"
    , weight = 1
    , radius = 5
  ) %>%
  addLayersControl(overlayGroups = c("counties")) %>%
  addMouseCoordinates() %>%
  setView(lng = 8.717, lat = 48.110, zoom = 5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment