Exploring the world with an interactive map in R, incorporating Shiny and leaflet

I'm currently attempting to integrate a Google layer as the base layer for a Leaflet map in Shiny R. To achieve this, I've been utilizing shinyJs to inject a JavaScript script into my R code and add the map. However, I'm facing an issue where I cannot access the map outside of the JavaScript code. When checking the JS console, it indicates that "the map container has already been initialized." Below is the reproducible code for the app:

###################
#### Library ######
###################
library(leaflet)
library(shiny)
library(shinythemes)
library(shinyjs)

setwd("D:\\R")

ui <- fluidPage(
  tags$head(
    tags$link(rel="stylesheet", href="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a5aca8afa5acbd89f8e7f9e7fa">[email protected]</a>/dist/leaflet.css"),
    tags$script(src="shared/shiny.js"),
    tags$script(src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAQvaBc5_RruTllCvOxy3i9YNFYlaDzaJ8"),
    tags$script(src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f131a1e19131a0b3f4e514f514c">[email protected]</a>/dist/leaflet.js"),
    tags$script(src='https://unpkg.com/leaflet.gridlayer.googlemutant@latest/Leaflet.GoogleMutant.js')
  ),
  sidebarLayout(
    sidebarPanel(
      actionButton(inputId = "button",
                   label = "coucou")
    ),
    mainPanel(
        leafletOutput("mymap")
    )
  #)
  ),
  tags$script(HTML('$(document).on("shiny:connected", function(){
  var mymap = L.map("mymap").setView([45.777222,3.087025],4);
  var roads = L.gridLayer.googleMutant({type : "satellite"}).addTo(mymap);
  var el = document.getElementById(mymap.id);
  Shiny.onInputChange("mymap",el);

})'))
)


server <- function(input, output) {

  observeEvent(input$button, {
    output$mymap <- renderLeaflet({
    leafletProxy("mymap", data =input$mymap) %>%
      addMarkers(45.777222,
               3.087025,
               "btn")
    })
  })

  observeEvent(input$mymap_click, {
    cat("vroum")
  })

}

shinyApp(ui = ui, server = server)

Answer №1

If you want to display a Google Map in your application, you can utilize the googleway package

library(shiny)
library(googleway)

ui <- fluidPage(
    google_mapOutput(outputId = "map", height = 600)
)

server <- function(input, output){

    output$map <- renderGoogle_map({
        google_map(key = 'your_api_key')
    })

    observeEvent(input$map_map_click, {
        print(input$map_map_click)
    })

}

shinyApp(ui, server)

Answer №2

For those wondering how to access the map, you can utilize the code below:

  var element = document.getElementById("mymap");
  var mapInstance = $(element).data("leaflet-map"));

However, incorporating the Google layer may not be straightforward due to the compatibility issues between Leaflet version 1.0.3 and the R package's use of version 0.7. Simply loading version 1.0.3 could result in compatibility problems.

I've been attempting the same task without success thus far. If you have managed to achieve this, I would greatly appreciate any insights you can provide.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenge with Vite, React, and MSW Integration

Having some trouble setting up MSW in a React application. It's unusual for me to come across issues like this. I've configured an environment variable VITE_MOCK set to true when running the yarn start:mock command. This should enable API mocking ...

Error encountered: The Jquery-ui functionality ceases to operate upon the completion of content

I'm utilizing the jQuery UI library to rearrange the items on my list. Initially, everything works smoothly without any issues. However, when I navigate to another page and then return to the page with my list, I encounter difficulties. It's wor ...

Executing filepicker.io Javascript API calls may lead to unsafe errors in Javascript

I am currently using AngularJS and encountering an issue when trying to call filePicker.pickAndStore from my Upload controller. Every attempt to use a filepicker.io API function triggers an "Unsafe Javascript attempt" error: The frame requesting access ...

What is the correct way to utilize "data:" in a jQuery AJAX call?

There seems to be an issue with my code within the deletePost function. The problem lies in the fact that $_GET['title'] is empty. Although I set the title value in the ajax using postTitle: $(this).siblings("h3.blog").text(), it doesn't see ...

Error encountered in jQueryUI Autocomplete: the function 'this.source' is not defined

I have been working on incorporating a live search feature that scans through keys in a JSON obtained from a public API. To achieve this, I am utilizing Jquery UI. However, I encountered the following error and I am uncertain about how to resolve it. Un ...

Stop users from refreshing or closing the window while an axios request is being processed

I'm in the process of creating a dynamic Web Application that involves utilizing Axios.get requests. Given that Axios operates asynchronously, my approach includes an async function along with await axios.all: async handleSubmit(){ const ...

Organizing an HTML layout

Looking for a way to sort a div structure based on a parameter, I came across a small JavaScript that seems to not work as expected. It appears that the sorting function is not parsing the values perfectly... This is the logic I am using for sorting: < ...

Is it possible to utilize the import feature to access and read a JSON file within a Next.js 13 API scenario?

Currently, in my Next.js 13 project, I am using the App Router feature to work with an API route that reads a file from a language folder within the resources directory. The code structure of this API is as follows: // app/api/file/[lang]/write/route.ts i ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

The use of PUPPETEER_DOWNLOAD_HOST has been phased out. It is recommended to use PUPPETEER_DOWNLOAD_BASE_URL moving forward. / Puppeteer

Trying to install puppeteer, I followed the installation guide. However, after a few seconds, I encountered this error: .../node_modules/puppeteer postinstall$ node install.mjs │ PUPPETEER_DOWNLOAD_HOST is deprecated. Use PUPPETEER_DOWNLOAD_BASE_URL ins ...

Examining an Array of Objects Based on Various Attributes

Looking to find a way to check if a similar object already exists in an array of objects. Specifically, I want to know if there is an object with the same make and model properties (Ford Focus): { make: 'Ford', model: 'Focus', co ...

I'm having difficulty implementing a vue-awesome icon on my project

I am attempting to utilize the standard window-close icon from vue-awesome. I have imported my vue-awesome using the following code: import 'vue-awesome/icons'; import Icon from 'vue-awesome/components/Icon.vue'; Vue.component('i ...

What is the method for incorporating an upward arrow into a select element, while also including a downward arrow, in order to navigate through options exclusively with

I have a select element that I have styled with up and down arrows. However, I am seeking assistance to navigate the options dropdown solely using these arrows and hide the dropdown list. Here is the HTML: <div class="select_wrap"> <d ...

Regular expression: Identify all instances of double quotes within a given string and insert a comma

Is there a way to transform a string similar to the following: ' query: "help me" distance: "25" count: "50" ' Into either a JavaScript object or a JSON string that resembles this: '{ query: "help me", distance: "25", count: "50" }' ...

Exploring the power of Foundation For Apps and Angular by seamlessly displaying dynamic data sourced from

I'm currently working with Foundation for Apps, a framework that incorporates elements of AngularJS. My goal is to display the content from a local JSON file by accessing it through a controller and rendering the results as 'cards'. Addition ...

Click the link to capture the ID and store it in a variable

Currently working on a project involving HTML and JavaScript. Two HTML pages ("people.html" and "profile.html") are being used along with one JavaScript file ("people.js") that contains an object with a list of names, each assigned a unique ID: var person ...

Having trouble with retrieving JSONP data? Unsure how to access the information?

Why do I keep getting a -403 error? https://i.stack.imgur.com/T53O9.png However, when I click on the link, I see this: https://i.stack.imgur.com/8GiMo.png How can I retrieve the message? ...

Effortlessly glide to a specific div ID upon page load using the URL address

One way to implement smooth scrolling to an anchor on page load is by using jQuery. Here's an example code snippet: $(function(){ $('html, body').animate({ scrollTop: $( $('#anchor1').attr('href') ).offset(). ...

What is the best method to set one div as active by default in jQuery UI Accordion?

$(window).load(function(){ $.fn.togglepanels = function(){ return this.each(function(){ $(this).addClass("ui-accordion ui-accordion-icons ui-widget ui-helper-reset") .find("h3") .addClass("ui-accordion-header ui-helper-reset ...

Generate pre-set components using fundamental building blocks

Can I predefine some props for components? In my Vuetify example, let's say I want to customize the v-btn component with specific props. This custom implementation would act as a child component while still providing all the functionalities of the par ...