Leaflet in R Shiny

4,983 views
Skip to first unread message

Mayank Aggarwal

unread,
Oct 3, 2013, 6:35:53 AM10/3/13
to shiny-...@googlegroups.com
Hi Joe

I was trying to replicate your example 

on my local machine . It seems I need to install package leaflet .. which I am unable to do so ... can you please guide me as to what needs to be done to replicate the example on my local machine


I was also fiddling with the leaflet on rcharts by ramnathan ... I sensed that you guys are basically using the same leaflet.js but implementation is in a different manner . Since, there is lack of documentation around the same , my idea requires more of your thoughts 

If any one else has done more work around it , please feel free to share your thoughts


Thanks
Mayank

Joe Cheng

unread,
Oct 3, 2013, 11:50:39 AM10/3/13
to shiny-...@googlegroups.com
Yes, that repo itself is the package. You can install it like so:

if (!require(devtools))
  install.packages('devtools')
devtools::install_github('leaflet-shiny', 'jcheng5')

Once you've done that you can run the example in the inst/example directory like a normal Shiny app. For the example app you'll need a couple of other dependencies as well:

if (!require(maps))
  install.packages('maps')
devtools::install_github('ShinyDash', 'trestletech')

Sorry that my library is so under-documented. It's on someone's list to polish it up but we haven't gotten to it yet.


--
You received this message because you are subscribed to the Google Groups "Shiny - Web Framework for R" group.
To unsubscribe from this group and stop receiving emails from it, send an email to shiny-discus...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Ramnath Vaidyanathan

unread,
Oct 3, 2013, 1:33:23 PM10/3/13
to shiny-...@googlegroups.com
To use Leaflet with rCharts, here is a detailed tutorial on creating the bikesharing network map


Hope this is useful.

Mayank

unread,
Oct 16, 2013, 11:59:24 PM10/16/13
to shiny-...@googlegroups.com
Hi Joe

When I am trying to install Shiny Dash ..  I am getting the following error

* installing *source* package 'ShinyDash' ...
** R
** inst
** preparing package for lazy loading
Error : object 'validateCssUnit' is not exported by 'namespace:shiny'
ERROR: lazy loading failed for package 'ShinyDash'
* removing '/usr/lib64/R/library/ShinyDash'
Error: Command failed (1)


Can you please suggest what needs to be done


Ramnathan - I tried yours long back .. It is great but I just happened to try Joe's app and seeing how it can be used further

Mayank

unread,
Oct 17, 2013, 3:37:04 AM10/17/13
to shiny-...@googlegroups.com
Able to do it. Thanks

Brent Sitterly

unread,
Oct 22, 2013, 3:40:35 PM10/22/13
to shiny-...@googlegroups.com
How did you get it to work?  I'm getting the same problem but haven't had any luck.

Joe Cheng

unread,
Oct 22, 2013, 7:31:51 PM10/22/13
to Brent Sitterly, shiny-...@googlegroups.com
That message means you're using a version of Shiny that's older than the ShinyDash package expects. (Probably the ShinyDash DESCRIPTION file should be updated to reflect the version of Shiny it depends on)

Just upgrade like this:

install.packages("shiny")

or for the brave:

devtools::install_github("shiny", "rstudio")


--

Mayank

unread,
Oct 24, 2013, 1:55:42 PM10/24/13
to shiny-...@googlegroups.com, Brent Sitterly
Hi Joe 


I am unable to add geojson objects to leaflet map... can you please guide as to what am i missing here

geojsonFeature <- '{
       "type": "Feature",
       "properties": {
         "name": "Coors Field",
         "amenity": "Baseball Stadium",
         "popupContent": "This is where the Rockies play!"
       },
       "geometry": {
         "type": "Point",
         "coordinates": [42.99404, -84.75621]
       }
     }'
     parser <- newJSONParser()
     map1$addgeoJson(toGeoJSON(parser$addData(geojsonFeature)))
     
     Error in func() : attempt to apply non-function

David Stephens

unread,
Nov 1, 2013, 9:15:28 AM11/1/13
to shiny-...@googlegroups.com, Brent Sitterly
Hi, 

I am trying to add a polygon to the map. Any pointers on how the arguments should be specified?

    opts=list(color='#4A9',)
    map$addPolygon(c(55,55,56,56),
                   c(0,1,1,0),
                   layerId=c(1),
                   options=opts,
                   defaultOptions=opts)

Thanks, Dave.

dimalvov

unread,
Dec 26, 2013, 7:21:58 AM12/26/13
to shiny-...@googlegroups.com
Hi Mayank, can you please share your solution on this?

dimalvov

unread,
Dec 26, 2013, 7:25:41 AM12/26/13
to shiny-...@googlegroups.com
Hi Brent, I got it - install shiny like this: devtools::install_github('shiny') since its not the latest version on CRAN.

John froeschke

unread,
Jan 14, 2014, 8:29:34 AM1/14/14
to shiny-...@googlegroups.com, Brent Sitterly
I'm wondering if this problem was resolved.  I'm trying to add a polygon to a leaflet map without success.

  opts=list(color='#4A9')
    map$addPolygon(
      c(25,-23,23,25),
      c(-89,-90,-88,-87),
      layerId=c(1),
    options=opts,
      defaultOptions=opts)

No error is reported but the polygon does not display. 

Udrescu Tudor

unread,
Jan 20, 2014, 8:57:05 AM1/20/14
to shiny-...@googlegroups.com
You have to supply the layerID parameter as string. Also make sure to get the latest version of the shiny leaflet package from GitHub, I recall there was a small bug in the addPolygon JS binding.

library(shiny)
library(leaflet)

runApp(
  list(
      server=function(input, output, session) {
        
        # create the map
        map <- createLeafletMap(session, 'map')
 
        observe({ 

            if(input$drawPoints == 0) {
              return(NULL)
            } else {
              
            map$clearShapes()
            
            opts=list(color='#4A9')
            
            map$addPolygon(
              c(48.99831, 49.08815, 49.08815, 48.99831, 48.99831),
              c(13.42666, 13.42666, 13.56383, 13.56358, 13.42666),
              layerId=c("1"),
              options=opts,
              defaultOptions=opts)
            
           }
        })
      },
      ui=basicPage(
        mainPanel(
          leafletMap("map", "100%", 550, initialTileLayer = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
                    initialTileLayerAttribution = HTML('&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'),
                    options = list(center = c(51.01, 8.68), zoom = 6, maxZoom = 10, minZoom=4, maxBounds = list(list(30,-20),list(68,90)))),
          actionButton("drawPoints", "Draw"))
      ))
)

John froeschke

unread,
Jan 21, 2014, 9:10:37 PM1/21/14
to shiny-...@googlegroups.com
Thanks very much, exactly what I needed.


On Thursday, October 3, 2013 6:35:53 AM UTC-4, Mayank wrote:
Message has been deleted

Kirk Hadley

unread,
Feb 16, 2014, 2:03:54 AM2/16/14
to shiny-...@googlegroups.com
Hi,

Is there a way to add a link in the hover/pop-up?


On Thursday, October 3, 2013 6:35:53 AM UTC-4, Mayank wrote:

Clancy Birrell

unread,
Feb 16, 2014, 11:22:14 AM2/16/14
to shiny-...@googlegroups.com, Brent Sitterly
Hi Joe, 

I'm attempting to plot a point geocoded by googlemapsapi using leaflet-shiny, however the point is off by about 500 - 1000m.
My hunch is that the projection for leaflet-shiny vs the WGS84 projection that google has output the lat longs is different and therefore causing the error in the point location on the leaflet map.
So i would like to update the projection of the map to EPSG:4326 but can't see any functions to do so in your github code?
Please help?
Regards,
Clancy.

Joe Cheng

unread,
Feb 17, 2014, 2:44:10 PM2/17/14
to jrcha...@gmail.com, shiny-...@googlegroups.com
Is it possible you created a function called "map" somewhere around there? That's what that error message appears to indicate.


On Sat, Feb 15, 2014 at 5:24 AM, <jrcha...@gmail.com> wrote:
Hi Joe,

I'm using your code as a base for my own, and specifically, I'm having issues with map$clearShapes within observe; when I comment it out, the app works fine except for the fact that the shapes don't go away when the user selects a different city. Everything else seems to work well.

Here's my error.


map$clearShapes : object of type 'closure' is not subsettable

Thank you so much for your help!

J.R.

Joe Cheng

unread,
Feb 17, 2014, 2:45:58 PM2/17/14
to Kirk Hadley, shiny-...@googlegroups.com
Yes, something like this should work:

as.character(tags$a(href="http://www.rstudio.com", target="_blank", "This is a link"))

You can just paste0() that together with whatever other content you have in the popup.


--

Joe Cheng

unread,
Feb 17, 2014, 2:47:07 PM2/17/14
to Clancy Birrell, shiny-...@googlegroups.com, Brent Sitterly
The geocoding should just be lat/long, right? That doesn't seem like it should relate to the projection. Are you using a custom tile layer? If so, perhaps that's where the projection mismatch is occurring? (I know very little about GIS...)

Clancy Birrell

unread,
Feb 17, 2014, 4:55:17 PM2/17/14
to Joe Cheng, Brent Sitterly, shiny-...@googlegroups.com

Thanks for the response.
I'm pretty sure leaflet shiny is setup as Mercator projection but Google geocoding uses latlong. Leafletjs has a method for updating but I couldn't find the command in leafet -shiny.

Joe Cheng

unread,
Feb 17, 2014, 7:13:58 PM2/17/14
to Clancy Birrell, shiny-...@googlegroups.com
According to this:

the default projection in Leaflet is EPSG:3857 aka Google Mercator aka Web Mercator aka WGS84 aka Pseudo Mercator.

My understanding is that a map projection can be thought of as the function that takes a latitude and longitude as input, and outputs an x,y coordinate. So Google Geocoding doesn't "use" a projection at all.

I seem to vaguely recall having to work around some RJSONIO precision issues; is it possible that the lat/long is correct in your R code, but incorrectly being truncated on its way to the browser? Can you try this by calling leaflet methods with hardcoded lat/long coordinates and seeing if they're correct? Or by passing two different set of coordinates that differ by a small but significant distance, and see if they end up being distinguishable on the map?

Clancy Birrell

unread,
Feb 17, 2014, 7:52:37 PM2/17/14
to Joe Cheng, shiny-...@googlegroups.com

Hiya Joe. Yeah they're definitely correct coords coming back from Google as I can use plotgooglemaps and or ggmap + ggplot2 and they're rendered correctly just getting adulterated by leaflet-shiny.

Kent Johnson

unread,
Mar 30, 2014, 7:03:58 PM3/30/14
to shiny-...@googlegroups.com, Brent Sitterly
I also struggled to get polygons to work. I have a data.frame with columns lat.start, lng.start, lat.end, lng.end, Count and I wanted to add a line to the map for each row of the data.frame. Here is the code that works:
    for (i in 1:nrow(uniqueTotals))
      bikeMap$addPolygon(c(uniqueTotals$lat.start[i], uniqueTotals$lat.end[i], 0), 
                     c(uniqueTotals$lng.start[i], uniqueTotals$lng.end[i], 0), 
                     layerId=list(as.character(i)),
                     options=list(list(weight=uniqueTotals$Count[i])))

A couple of things to note:
  • The last point of the polygon is not used, so I added an extra 0 point at the end. This may be a bug in bindings.js where it pops the last point before calling L.polygon().
  • layerId must be a list even though it has only one element; otherwise bindings.js uses *characters* of layerId as the actual id, so it just uses the first character and only 10 lines plot.
  • options has to be a list of lists.

Franco Peschiera

unread,
Jun 14, 2014, 6:49:15 PM6/14/14
to shiny-...@googlegroups.com, sitt...@gmail.com
Hello Kent,

When using something similar to your code I do not get my polygon to show only when it is one polygon (when plotting several polygons, this works correctly). I almost sure it has something to do with your second bullet point ("layerId must be a list even though it has only one element;")... I have tried giving everything as input: converting it to list, to character. to integer... nothing.
what was the thing you do to solve this problem?

Thanks!
Reply all
Reply to author
Forward
0 new messages