klupido
klupido

Reputation: 21

How to offset polylines?

I am currently mapping several city connections (polylines) using leaflet in R/shiny which works perfectly fine. However, there are several lines on top of each other and I'd like to be able to offset these overlapping lines.

There is already a plug-in by bbecquet for leaflet that does the job but it's not implemented in the R package (yet?).

https://github.com/bbecquet/Leaflet.PolylineOffset

My current solution is pretty much "hands-on" as I simply shift the lines depending on the zoom-level.

# temp2 is a SpatialLinesDataFrame
negs <- as.matrix(coordinates(temp2[1,])[[1]][[1]])
negs[,1] <- (negs[,1])+exp(input$map_zoom)
negs[,2] <- (negs[,2])+exp(input$map_zoom) 
temp2@lines[[1]]@Lines[[1]]@coords[] <- negs

See example how it currently looks like.

enter image description here

Does any one have a better idea or knows how I could use the PolylineOffset plug-in in R?

Upvotes: 2

Views: 1709

Answers (1)

Anton
Anton

Reputation: 71

In the ui part of shiny add this:

tags$head(
    tags$script(src="leaflet.polylineoffset.js")
)

And place the javascript file in the www folder of your shiny app. Then in the server part use the offset like this:

leafletProxy("my_map") %>%
addPolylines(data=coords, weight=1, options=list(offset=3))

In the example, there is already a map initialised called "my_map" and coords contains the coordinates of the polylines. The offset is in pixels indpendent of zoom level.

bbecquet did great work on this plugin, but unfortunately it didn't work properly for me. I adjusted the javascript code somewhat to resolve the issues. You can find my version here: modified offset javascript

It works only with the R leaflet package version 2 and higher which is based on a more recent version of leaflet.

Upvotes: 2

Related Questions