logo
down
shadow

How to correctly clearShapes in Leaflet in a Shiny app


How to correctly clearShapes in Leaflet in a Shiny app

By : Prince Devasitham
Date : November 20 2020, 11:01 PM
I wish this help you Your first issue is solved by using clearMarkers() rather than clearShapes().
As to the other issue you pointed out, leaflet struggles with empty (and NA) data. When you deselect all the values, your data.frame obviously becomes empty. A simple check for this to stop leaflet trying to plot it will solve this issue.
code :
library(shiny)
library(dplyr)
library(leaflet)

my_df <- data.frame(lat = 34.72 + rnorm(1000, sd = .18), 
                    lng = -92.5 + rnorm(1000, sd = .33), 
                    category = c(rep("A", 300), rep("B", 300), rep("C", 400)))

ui <- bootstrapPage(
    tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
    leafletOutput("map", height = '100%', width = '100%'),
    absolutePanel(top = 10, right = 10, 
                 checkboxGroupInput("choices", "Choices"
                                     , choices = list("A","B","C")
                                     , selected = c("A","B","C")),
                 verbatimTextOutput("my_rows")
    )
)

server <- function(input, output) {

    filteredData <- reactive({ 
        my_df %>% filter(category %in% input$choices) 
        })

    output$map <- renderLeaflet({ 
        leaflet() %>% 
            addTiles() %>% 
            setView(lat = 34.72, lng = -92.5, zoom = 9) 
        })

    observe({

        df <- filteredData()

        ## check for empty dataframe
        if(nrow(df) == 0){
            leafletProxy("map", data = df) %>% 
            clearMarkers()
        }else{
            leafletProxy("map", data = df) %>% 
                clearMarkers() %>% 
                addCircleMarkers(radius = 6, weight = 1
                                 , fillColor = "red", fillOpacity = 0.3)
        }

    })

    output$my_rows <- renderPrint({ 
        filteredData() %>% 
            nrow() 
        })
}

shinyApp(ui = ui, server = server)


Share : facebook icon twitter icon
Can't display Leaflet HTML through R-Shiny (404 error). How to integrate KML file with rMaps or leaflet-shiny?

Can't display Leaflet HTML through R-Shiny (404 error). How to integrate KML file with rMaps or leaflet-shiny?


By : Umut Kayatuz
Date : March 29 2020, 07:55 AM
seems to work fine I think there may be a small issue in the rMaps library. If you inspect the config.yml file https://github.com/ramnathv/rCharts/blob/master/inst/libraries/leaflet/config.yml you will see that for content delevery network (cdn) there is reference to "http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js". This KML reader is a plugin for leaflet from https://github.com/shramov/leaflet-plugins/blob/master/layer/vector/KML.js. When content is delivered locally:
code :
  css: [external/leaflet.css, external/leaflet-rCharts.css, external/legend.css]
  jshead:
    - external/leaflet.js
    - external/leaflet-providers.js
    - external/Control.FullScreen.js
require(yaml)
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
rMapsConfig <- yaml.load_file(file.path(leafletLib, "config.yml"))
# add a kml library
kmlLib <- readLines("http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js")
write(kmlLib, file.path(leafletLib, "external", "leaflet-kml.js"))
# add the library to config.yml
rMapsConfig$leaflet$jshead <- union(rMapsConfig$leaflet$jshead , "external/leaflet-kml.js")
write(as.yaml(rMapsConfig), file.path(leafletLib, "config.yml"))
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addKML('leaflet/placemark.kml')
# temp copy http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml
# to rMaps
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))

# finally try the map
map1

# remove the temp file 
file.remove(file.path(leafletLib, 'placemark.kml'))
require(rMaps)
map1 = Leaflet$new()
map1$setView(c(45.5236, -122.675), 13)
map1$tileLayer("http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png")
map1$addAssets(css = NULL, jshead = 'http://harrywood.co.uk/maps/examples/leaflet/leaflet-plugins/layer/vector/KML.js')
map1$addKML('leaflet/placemark.kml')
leafletLib <- file.path(find.package("rMaps"), "libraries", "leaflet")
sampleKml <- readLines('http://kml-samples.googlecode.com/svn/trunk/kml/Placemark/placemark.kml')
write(sampleKml, file.path(leafletLib, 'placemark.kml'))
# finally try the map
map1

# remove the temp file 
file.remove(file.path(leafletLib, 'placemark.kml'))
Handling `'createWebDependency' is not an exported object from 'namespace:shiny'` error in Leaflet Shiny

Handling `'createWebDependency' is not an exported object from 'namespace:shiny'` error in Leaflet Shiny


By : user3623260
Date : March 29 2020, 07:55 AM
may help you . According to THIS thread you might need to update your shiny version. If that doesn't help, could you add your output from "sessionInfo()" ?
R Shiny Leaflet - clearShapes() not working?

R Shiny Leaflet - clearShapes() not working?


By : Asem Youssef Abdel S
Date : March 29 2020, 07:55 AM
Hope that helps The culprit is renderUI() in this case. Because you used renderUI(), the rendering of the slider is delayed. By the time the observer runs for the first time, the slider is not there yet, and input$time_span is initially NULL, so filter_df() returns an empty data frame. I don't see a particular reason of using renderUI() in this case (perhaps you have a reason), and you can either just move sliderInput() to ui.R, or check if (is.null(input$time_span)) before you add circles to the map, or change observe() to observeEvent() (if you are using a recent version of shiny):
code :
observeEvent(input$time_span, {
    points_df <- ddply(filter_df(), c("lat", "lon"), summarise, count = length(timestamp))
    cat(nrow(points_df))
    leafletProxy("map", data = points_df) %>% clearShapes() %>% addCircles()
})
clearShapes() not working -- leaflet() for R

clearShapes() not working -- leaflet() for R


By : arun kumar
Date : March 29 2020, 07:55 AM
To fix this issue Looks like there is an issue when filteredData() is empty. You can trying adding an if/else:
code :
if(nrow(filteredData())==0) { leafletProxy("map") %>% clearShapes()} 
else {
    leafletProxy("map", data = filteredData() ) %>% clearShapes() %>%
      addCircles(radius = 1, color = "red", group = "circles")
    }
df[as.character(df$Source) %in% input$set, ]
R/Shiny: Changed from readOGR to read_sf and shiny leaflet popups broke

R/Shiny: Changed from readOGR to read_sf and shiny leaflet popups broke


By : user3667347
Date : March 29 2020, 07:55 AM
this will help Just in case anyone else ever encounters this sort of problem when switching from readOGR to read_sf.... I bumbled into a solution to this popup issue through the process of elimination and updated the question above with comments to explain where I made the changes.
For most of my popups, just adding "stringsAsFactors = TRUE" to read_sf sorted out the issue (the default for read_sf is the opposite of readOGR). In the case of my more complex popup that was the product of a further geojoin, I needed to change the placeref column back to a factor after the join:
Related Posts Related Posts :
  • Extract single plot from ggplot with facet_grid
  • R: Subtract values from rows based on another column
  • Data Frame Transcode 1-0
  • Why can't we use . as a parameter in an anonymous function with %>%
  • How does R reference unassigned values?
  • How to interpret ACF plot y-axis scale in R
  • Naming resulting data.table columns after aggregation in R
  • can't write timestamps in PostgreSQL using RPostgres dbWriteTable
  • Why doesn't "mar" argument to plot.default get used?
  • How to extract dimension of a submatrix from a bigger matrix using R?
  • Area estimation using image in R
  • Building a symmetric binary matrix
  • Change color and add shape to lines on ggplot2 geom_freqpoly
  • Count event occurrence and assign it to individuals according to date and place of interview
  • ggplot2 is mutating/transforming size variables -- how to get back original data?
  • How to output literal backticks in knitr::spin
  • geom_text how to position the text on bar as I want?
  • How to escape the symbol of percentage '%' in r?
  • How to get R plot to plot variable on heat.color scale
  • Dynamically selecting principal components from the PCA output
  • Replicate a regression using a random subset of data each time and check distribution of regression coefficients?
  • How to find a string in a vector in r?
  • How to replace outliers with NA having a particular range of values in R?
  • rearrange data: convert from water year to calendar year
  • Plot multiple graphs on one plot in R within loop
  • Unconditional Probability Calculation in R
  • Calculate & add column length_of_time from date column in R
  • Asterisk in ggplot's annotate()
  • How to copy a row from a data frame to a matrix in R?
  • Importing a similar column (eg. pH column) from 60 csv files thru use of loop and making a matrix .
  • Reading text file with multi-char delimiter to a list in R
  • ggplot2 scale colours for heatmap
  • Looking to save a 3D spectrograph generated by SeeWave as .STL or similar in R
  • Separating three dimensional array by the stratifying variable
  • "Object '...' not found when referenced object is a nested function in R
  • NetLogo 5.3.1 and R 3.3.1 on Mac 10.10.6 headless exception
  • Extract unique values from column in dataframe, grouped by ID
  • Stacked Bar Chat (ggplot) in R:: Trying to create more than one bar in the chart
  • R: Creating a function to merge two columns
  • Error in knearest(Darr, P_set, K) : object 'knD' not found
  • Determining least significant predictor in Linear Regression Model with R
  • listcolumns and multidplyr
  • How to check for the presence of a location in a sentence in R?
  • Using mapply over a matrix when the function makes use of elemets' location in the matrix
  • R - stratified sampling for Person Period file
  • Merging two xts to create NAs at certain time stamps
  • How to subset data in a loop in R?
  • How to use sprintf to show string "\t"?
  • Subset Columns based on partial matching of column names in the same data frame
  • R Extract number from string
  • How to put 2 boxplot in one graph in R without additional libraries?
  • ggplot omits polygon holes
  • ggplot2 geom_boxplot side by side with facets
  • outlier labels incorrectly assigned with ggplot2 box plot
  • capture column pattern frequency
  • R remove tags starting with U
  • R, dplyr and snow: how to parallelize functions which use dplyr
  • R: Separate String Without Delimiter (like Fixed Width in Excel)
  • In R, is there a parsimonious or efficient way to get a regression prediction holding all covariates at their means?
  • Determine mode locations of the kernel density estimate of multimodal univariate data
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com