How to add search box on tmap_leaflet linked to google street map using R?

I am new to using R and leaflet.I have created a map using tmap_leaflet. I am satisfied with the map but I think it will even better if I add a search box function to allow users to search their cities.

I have looked around seen people suggest leaflet-custom-searchbox and other plugin.

It seems like some are using html code and others. I am wondering if it is possible to add a search bar to my map using R.

I would like to export html file from R and eventually embed the map on a website. My hope is that when people use the search bar that is on the map (on the website), they will be able to get the same results you get on google maps.

This is the code for my map


OCmap <- tm_shape(map)+
         tm_fill(
            alpha = 0.4
         )+
         tm_shape(districtsg)+
         tm_borders(col = "white")
# Map 1
OCmap %>%  tmap_leaflet() %>%
   setView(lng = -1.0232,lat=7.9465,zoom = 6) %>% #lat and long of my district
   addProviderTiles('Esri.WorldGrayCanvas', group='Grayscale Map') %>% 
   addProviderTiles('OpenStreetMap', group='Street Map') 

I'd appreciate input on how to achieve the result I want.Thanks in advance.

Ann,

this is not your first question here, and you may notice that you will get better answers if you provide a reproducible code.

As your code is not exactly reporducible allow me to use the old favorite - the North Carolina shapefile from {sf} package; I have kept the vast majority of your code, replacing Singapore by North Carolina.

The key part is using leaflet.extras::addSearchOSM() call. You may want to specify collapsed = FALSE, and you may not - this will depend on your application, try both & see for yourself.

Note that it is in principle possible to use leaflet.extras::addSearchGoogle() and have the search executed by Google, thus guaranteeing your result will be exactly the same as on Google Maps. This would however require you to register for Google API, and bear the cost of geocoding (which is a paid service).

library(sf)
library(tmap)
library(leaflet)
library(leaflet.extras)

# NC counties - a shapefile shipped with the sf package
shape <- st_read(system.file("shape/nc.shp", package ="sf")) %>% 
  st_transform(shape, crs = 4326) # WGS84, just because...

# NC leaflet
NCmap <- tm_shape(shape) + tm_borders("red")

# Map 1
NCmap %>%  
  tmap_leaflet() %>%
  addProviderTiles("Stamen.Toner") %>% 
  leaflet.extras::addSearchOSM(options = searchOptions(collapsed = FALSE))

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.