Skip to content

Instantly share code, notes, and snippets.

@lauvshree
Last active June 5, 2020 04:01
Show Gist options
  • Save lauvshree/08aae86efdb471271448ef5841dbfbe0 to your computer and use it in GitHub Desktop.
Save lauvshree/08aae86efdb471271448ef5841dbfbe0 to your computer and use it in GitHub Desktop.
Interactive Map In R

Lab: Creating an Interactive Map in R

Welcome to the 2nd RStudio lab, in which we create an interactive map using two libraries. Shiny, which is an amazing library for prototyping interactive user interfaces in R and Leaflet which allows us to use OpenStreetMap data to create an interactive map. Shiny will use Leaflet as one of it’s UI components (like any other UI component like button, slider or text field).

  1. For this exercise we need to install two packages - shiny and leaflet. To install the packages, copy, paste and execute the following command into the bottom left Console window.
install.packages("shiny")

install.packages("leaflet")

If you don't see any error messages, it means the packages have been successfully installed.

  1. Paste the following code into a new R edit window in RStudio:
library(shiny)
library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))
names(r_colors) <- colors()

ui <- fluidPage(
        leafletOutput("mymap"),
        p(),
        actionButton("recalc", "New points")
    )

server <- function(input, output, session) {
            points <- eventReactive(input$recalc, {
                points = cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)
                return(points)}, ignoreNULL = FALSE)

        observeEvent(input$Map_shape_click, { # update the location selectInput on map clicks
            output$coordinates <- renderText({ 
                "You have selected this"
            })
            })
        output$mymap <- renderLeaflet({
            leaflet() %>%
            addProviderTiles(providers$Stamen.TonerLite,
            options = providerTileOptions(noWrap = TRUE)
            ) %>%
            addMarkers(data = points())
        })

}

shinyApp(ui, server)
  1. Select all the code and click on the Run button on top.

You’ll see the following application appear:

  1. If you click New points, a new set of random points will be generated and displayed.

  2. Now let's change the code to display the list of points on the user interface. To do this, we will change the behavior of this application by changing the “server” object. Therefore, please replace the some of the code in the the original code as here under.

Replace,

## Original code
ui <- fluidPage(	
  leafletOutput("mymap"),	
  p(),	
  actionButton("recalc", "New points")	
)

with

## Code to replace

ui <- fluidPage(
  leafletOutput("mymap"),
  p(),
  actionButton("recalc", "New points"),
  p(),
  textOutput("coordinates")
)

and also replace

## Original code

points <- eventReactive(input$recalc, {	
    points = cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)	
    return(points)	
  }, ignoreNULL = FALSE)

with

## Code to replace

points <- eventReactive(input$recalc, {    
    points = cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)    
    output$coordinates <- renderText({       
      points      
    })    
    return(points)    
  }, ignoreNULL = FALSE)

such that the complete code section looks as follows:

New Interactive Map Code

library(shiny)

library(leaflet)

r_colors <- rgb(t(col2rgb(colors()) / 255))

names(r_colors) <- colors()

ui <- fluidPage(  
  leafletOutput("mymap"),  
  p(),  
  actionButton("recalc", "New points"),  
  p(),  
  textOutput("coordinates")  
)

server <- function(input, output, session) {
  
  points <- eventReactive(input$recalc, {    
    points = cbind(rnorm(40) * 2 + 13, rnorm(40) + 48)    
    output$coordinates <- renderText({       
      points      
    })    
    return(points)    
  }, ignoreNULL = FALSE)
    
  observeEvent(input$Map_shape_click, { # update the location selectInput on map clicks    
    output$coordinates <- renderText({       
      "You have selected this"      
    })    
  })
  
  output$mymap <- renderLeaflet({    
    leaflet() %>%      
      addProviderTiles(providers$Stamen.TonerLite,                       
                       options = providerTileOptions(noWrap = TRUE)                       
      ) %>%      
      addMarkers(data = points())    
  })  
}

shinyApp(ui, server)
  1. If you now select all the code and click on Run, you’ll notice a list of coordinate pairs which updates every time you click the New points button

This concludes this lab, we hope that you had fun! If you want to know more about Shiny and Leaflet, please visit the following links:

https://shiny.rstudio.com/

https://rstudio.github.io/leaflet/

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