【R】Shinyとleafletで地図上の座標取得
2019年12月13日
Shinyとleafletを使用して、地図上の座標(latitude longitude)を取得します。
library(shiny)
library(leaflet)
library(htmlwidgets)
ui <- fluidPage(
leafletOutput("map"),
br(),
verbatimTextOutput("out"),
verbatimTextOutput("out2")
)
server <- function(input, output, session) {
output$map <- renderLeaflet({
leaflet() %>%
addProviderTiles("OpenStreetMap.Mapnik") %>%
setView(135,35, zoom = 7) %>%
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])
}
})
## Observe mouse clicks and add circles
observeEvent(input$map_click, {
click <- input$map_click
clat <- click$lat
clng <- click$lng
output$out2 <- renderText({
validate(need(input$map_click, FALSE))
paste0("Lat: ", clat,
"\nLng: ", clng)
})
leafletProxy('map') %>%
addCircles(lng=clng, lat=clat, group='circles',
weight=1, radius=300, color='black', fillColor='green',
fillOpacity=0.2, opacity=1)
})
}
shinyApp(ui, server)