6

I want to access the current mouse position in a leaflet map in shiny. When using shiny you can get the current coordinates of a click event using input$MAPID_click, which contains latitude and longitude of the click. Similarly I want to have input$MAPID_mouseover with a list of the current latitude and longitude of the mouse cursor.

mapview::addMouseCoordinates(map) displays the coordinates in the leaflet map. It uses map.latlng.lng and map.latlng.lat, but I couldn't figure out, how to adapt the code to return a list with the coordinates instead of displaying them.

Ideally this code should work:

library(shiny)
library(leaflet)

ui <- fluidPage(
  leafletOutput("map"),
  br(),
  verbatimTextOutput("out")
)

server <- function(input, output, session) {
  output$map <- renderLeaflet({
    leaflet() %>% addTiles()
  })

  output$out <- renderPrint({
    validate(need(input$map_mouseover, FALSE))
    str(input$map_mouseover)
  })
}

shinyApp(ui, server)

3 Answers 3

7

Using onRender from htmlwidgets, you can add some javascript to pass the coordinates from mousemove to a Shiny input, based on this article.

library(shiny)
library(leaflet)
library(htmlwidgets)

ui <- fluidPage(
    leafletOutput("map"),
    br(),
    verbatimTextOutput("out")
)

server <- function(input, output, session) {
    output$map <- renderLeaflet({
        leaflet()  %>%
            addProviderTiles("OpenStreetMap.Mapnik") %>%
            setView(-122.4105513,37.78250256, zoom = 12) %>%
            onRender(
                "function(el,x){
                    this.on('mousemove', function(e) {
                        var lat = e.latlng.lat;
                        var lng = e.latlng.lng;
                        var coord = [lat, lng];
                        Shiny.onInputChange('hover_coordinates', coord)
                    });
                    this.on('mouseout', function(e) {
                        Shiny.onInputChange('hover_coordinates', null)
                    })
                }"
            )
    })

    output$out <- renderText({
        if(is.null(input$hover_coordinates)) {
            "Mouse outside of map"
        } else {
            paste0("Lat: ", input$hover_coordinates[1], 
                   "\nLng: ", input$hover_coordinates[2])
        }
    })
}

shinyApp(ui, server)

enter image description here

2
  • how did you make that gif? It looks awesome! Commented Apr 5, 2018 at 1:58
  • 3
    @aspiringurbandatascientist thanks! there's probably an easier way, but I take a screen recording with quicktime and then make a gif with picgif lite Commented Apr 5, 2018 at 16:35
0

Why doesn't R leaflet recognize mousemove? We should be able to:

observeEvent(input$map_mousemove, {

    coords <- unlist(input$map_mousemove)
})

And extract longitude and latitude accordingly. This observer works with click event anyhow, which is also part of the Map Interaction events

0
var map=L.map('map').setView([21.14,79.08],5); 
map.on('click', function(e) {
    l1=e.latlng.lat //get lat long of mouse click
    l2=e.latlng.lng

map.on('mousemove',function(e1){
        var lat=e1.latlng.lat;//get live coordinates of mouse movement
        var lng=e1.latlng.lng;
        map.removeLayer(rectangle)//to remove previous loop rectangle
        rectangle=L.rectangle([[l1,l2],[lat,lng]]).addTo(map);
        console.log(lat, lng)
    })

}) //Here first click anywhere on map, the coordinates will be stored in l1 and l2. Then simply move mouse, you will see rectangle getting stretched as you move so a rectangle will be formed of any shape by user.

Not the answer you're looking for? Browse other questions tagged or ask your own question.