TransWikia.com

R / Leaflet obtain clicked coordinates

Geographic Information Systems Asked by Manuel Chirouze on April 4, 2021

I have a fairly simple leaflet project in RStudio

library(rgdal)
library(leaflet)
library(htmlwidgets)

#load data/layers
m = leaflet() %>% {add polygons....}
saveWidget(m, file="HTML_File.html", selfcontained = F)

The resulting HTML page displays nicely, but I would want to respond to a click event by adding a pop-up that provides the lat / lon of the point clicked, as well as the attribute of the top-most layer.

I have no idea how to go about it. I noticed that the leaflet.js script that gets exported has code to handle double clicks. I tried to hack that code to provide an alert, along the lines of

alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)   

but clearly I don’t know what I’m doing.

2 Answers

Looks like you need more powerful tool to handle your problem. The solution in R may be using Shiny - basics in this link: https://rstudio.github.io/leaflet/shiny.html

input$MAPID_click is an event that is sent when the map background or basemap is clicked. The value is a list with lat and lng.

Correct answer by pajonk on April 4, 2021

Since I struggled to find this answer, in your server block, you need something like this:

observe({
    click = input$map1_click
    if(is.null(click))
        return()
    text<-paste("Latitude: ", click$lat, ", Longtitude: ", click$lng)
    text2<-paste("You've selected point ", text)
    map1_proxy = leafletProxy("map1") %>%
        clearPopups() %>%
        addPopups(click$lng, click$lat, text)
    output$Click_text<-renderText({
        text2
    })

Answered by Pat Lorch on April 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP