How to Connect Google Earth Engine with R Shiny

[This article was first published on Tag: r - Appsilon | Enterprise R Shiny Dashboards, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Google Earth Engine in R Shiny Thumbnail

Visualizing spatial data is always more challenging than it seems at first. There are too many moving parts, and the whole thing can quickly slow down your dashboard. Today you’ll learn how to connect Google Earth Engine with R Shiny. We’ll start by signing up for a free GEE account and configuring everything on the R end.

Want to integrate plain Google Maps in R Shiny dashboards? Our detailed google maps guide has you covered.

Table of contents:


How to Setup Google Earth Engine with R

Before you can connect Google Earth Engine with R Shiny, you’ll have to register for a GEE account. It’s completely free, but the registration page states it could take some time for your account to get approved. In our experience registration was a breeze, as we got a confirmation mail seconds after submitting:

Image 1 - Google Earth Engine registration mail

Image 1 – Google Earth Engine registration mail

Once that’s done, you’ll have to install the rgee R package. Now, R isn’t officially supported by the Google Earth Engine (only JavaScript and Python), so this package serves as a bridge. It allows you to write R code that essentially boils down to Python behind the scenes.

But how can R call Python code? We have a complete guide on using R and Python together.

Use the following command to install the rgee package:

install.packages("rgee")

The setup isn’t done yet. You’ll have to load the package and call the ee_install() function. It will create a Python virtual environment and install all Python dependencies for you. It goes without saying, but you should have Python 3 installed before running the code snippet below:

library(rgee)
rgee::ee_install()

We’re using Miniforge, a minimal distribution of Anaconda, and the above snippet worked without any issues.

The final step in this setup section is to call the ee_Initialize() function. It will do all the heavy lifting for you – initialize the previously created Python virtual environment and install all the required libraries:

library(rgee)
ee_Initialize()

Here’s what you should see in RStudio:

Image 2 - Initializing Python virtual environment for rgee

Image 2 – Initializing Python virtual environment for rgee

After a couple of seconds, a new browser window will open asking you to authenticate with a Google account that is connected with the Google Earth Engine service:

Image 3 - Authenticating Google account for Python libraries

Image 3 – Authenticating Google account for Python libraries

Once you click on Allow, you will get an authentication code, as shown in the image below:

Image 4 - Google account authentication code

Image 4 – Google account authentication code

And that’s it – paste the code into the R console when prompted and hit Enter:

Image 5 - Pasting Google account authentication code in R console

Image 5 – Pasting Google account authentication code in the R console

The authentication part is now complete. The only thing left to do is to specify a directory where Google Earth Engine will store everything:

Image 6 - Google Earth Engine local root directory

Image 6 – Google Earth Engine local root directory

Once that’s out of the way, you have everything needed to connect Google Earth Engine with R Shiny. Let’s see how it works in plain R first.

How to Render a Google Earth Map with R

The hard part is now over and we’re ready to have some fun with Google Earth Engine in R. The example you’ll see is quite basic, and can be found on the official package GitHub page.

It’s sort of a Hello World of Google Earth Engine program in R but will be enough to understand the fundamentals.

First, we’ll write a function createTimeBand that adds a band containing image data as years since 1991. Then, we map the time band creation helper over the night-time lights collection image dataset.

Finally, we will compute a linear fit over the series of values at each pixel, visualizing the y-intercept in green, and positive/negative slopes in red/blue:

library(rgee)

createTimeBand <- function(img) {
  year <- ee$Date(img$get("system:time_start"))$get("year")$subtract(1991L)
  ee$Image(year)$byte()$addBands(img)
}

collection <- ee$
  ImageCollection("NOAA/DMSP-OLS/NIGHTTIME_LIGHTS")$
  select("stable_lights")$
  map(createTimeBand)

col_reduce <- collection$reduce(ee$Reducer$linearFit())
col_reduce <- col_reduce$addBands(
  col_reduce$select("scale")
)
ee_print(col_reduce)
Image 7 - Google Earth Engine program output

Image 7 – Google Earth Engine program output

From here, it’s easy to create a map. First, we have to center it around some latitude and longitude and give it the value for zoom. Then, we’ll overlay the normal Google Earth map with our custom col_reduce layer:

Map$setCenter(9.08203, 47.39835, 3)
Map$addLayer(
  eeObject = col_reduce,
  visParams = list(
    bands = c("scale", "offset", "scale"),
    min = 0,
    max = c(0.18, 20, -0.18)
  ),
  name = "stable lights trend"
)

Here’s what the finished map looks like:

Image 8 - Google Earth Engine map in R

Image 8 – Google Earth Engine map in R

That’s amazing, but how can we make this map interactive in R Shiny? That’s what the next section covers.

Connect Google Earth Engine with R Shiny – Start Here

R Shiny is our favorite R package for creating interactive dashboards, so naturally, we want to see if it’s possible to connect R Shiny with Google Earth Engine.

Spoiler alert: It is, and the syntax will be near-identical to what we covered in the previous section. There’s no renderGoogleEarthEngine function available, unfortunately, so we’ll have to use the Leaflet package to render the map.

Our dashboard will have two panels:

  1. sidebarPanel – Contains the configurable values for latitude and longitude that update the map on the button click.
  2. mainPanel – Contains the Google Earth Engine map rendered by Leaflet.

Here’s the code for the entire Shiny app. There’s nothing that you should find unclear if you’ve read the previous section:

library(rgee)
library(leaflet)
library(shiny)

createTimeBand <- function(img) {
  year <- ee$Date(img$get("system:time_start"))$get("year")$subtract(1991L)
  ee$Image(year)$byte()$addBands(img)
}

collection <- ee$
  ImageCollection("NOAA/DMSP-OLS/NIGHTTIME_LIGHTS")$
  select("stable_lights")$
  map(createTimeBand)

col_reduce <- collection$reduce(ee$Reducer$linearFit())
col_reduce <- col_reduce$addBands(
  col_reduce$select("scale")
)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput(inputId = "in_latitude", label = "Latitude", value = 9.08203, min = -90, max = 90, step = 0.1),
      numericInput(inputId = "in_longitude", label = "Longitude", value = 47.39835, min = -180, max = 180, step = 0.1),
      actionButton(inputId = "reposition", label = "Reposition Map")
    ),
    mainPanel(
      leafletOutput(outputId = "map")
    )
  )
)


server <- function(input, output) {
  map <- eventReactive(input$reposition,
    {
      Map$setCenter(input$in_latitude, input$in_longitude, 3)
      Map$addLayer(
        eeObject = col_reduce,
        visParams = list(
          bands = c("scale", "offset", "scale"),
          min = 0,
          max = c(0.18, 20, -0.18)
        ),
        name = "stable lights trend"
      )
    },
    ignoreNULL = FALSE
  )

  output$map <- renderLeaflet({
    map()
  })
}

shinyApp(ui = ui, server = server)
Image 9 - R Shiny dashboard rendering the Google Earth Engine map

Image 9 – R Shiny dashboard rendering the Google Earth Engine map

Yes, it’s that easy. We’ve covered a lot of ground, so let’s make a short recap next.


Summary of R Shiny + Google Earth Engine

Today you’ve learned how to connect Google Earth Engine with R Shiny. There are a lot of setups involved, but we hope it wasn’t too tedious to follow. You can certainly use Google Earth Engine in your Shiny dashboards to overlay interesting layers around the base map. We went over a simple example, but encourage you to experiment further on your own.

Share your results with us on Twitter – @appsilon. We’d love to see what you come up with.

Want to dive deeper into Leaflet? Our detailed guide is all you need to make stunning geomaps.

The post How to Connect Google Earth Engine with R Shiny appeared first on Appsilon | Enterprise R Shiny Dashboards.

To leave a comment for the author, please follow the link and comment on their blog: Tag: r - Appsilon | Enterprise R Shiny Dashboards.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)