Search code examples
rshinyr-leaflet

any good library to search on the basis of long and latitude?


I have a requirement where I have some cities' longitude and latitude.

Bangalore - 12.9539974,77.6309395
Chennai - 13.0473748,79.9288083
Delhi - 28.6921165,76.8079346
Mumbai - 19.0821978,72.741098

I have created an input box that has some cities listed down

enter image description here

Based on this input I need to zoom into these cities.

How can I do this?


Solution

  • You can do this with leaflet

    library(dplyr)
    library(shiny)
    library(leaflet)
    
    data_cities = data.frame(
      city = c('Bangalore', 'Chennai', 'Delhi', 'Mumbai'),
      lat = c(12.9539974, 13.0473748, 28.6921165, 19.0821978),
      lng = c(77.6309395, 79.9288083, 76.8079346, 72.741098)
    )
    
    ui <- fluidPage(
      selectInput("select_city", label = "Select city", choices = data_cities$city),
      leafletOutput("map")
    )
    
    server <- function(input, output) {
      # Initiate the map
      output$map <- renderLeaflet({
        leaflet() %>% 
          addTiles(options = providerTileOptions(noWrap = TRUE)) 
      })
      
      #Zoom when select city
      observeEvent(input$select_city, {
        selected_city_data <- data_cities %>%
          filter(city == input$select_city)
        
        leafletProxy("map") %>%
          setView(lng = selected_city_data$lng, lat = selected_city_data$lat, zoom=8) 
        
      })
    }
    shinyApp(ui = ui, server = server)