zesla
zesla

Reputation: 11813

how to show multiple texts on pop-up in leaflet map in r

I made an interactive map using leaflet package in r. I created an example dataset as below. There are two cities, London and Birmingham. 3 tweets from London and 2 from Birmingham. What I want to do is click on marker on map to show all the tweets at that location. However, I could only show the first tweet from that location clicked on pop-up.

What I want to show is all the tweets at the clicked location. Ideally something like a table or just a list of tweets. This is just a dataset I made up. My real dataset has many cities, some of which has over 10 tweets. Does anyone know how to achieve that? Thanks a lot for help.

My code is below:

library(leaflet)
library(dplyr)
data_map = data.frame(lat=c(51.50735, 51.50735, 51.50735,52.48624,52.48624),
                      lon=c(-0.1277583,-0.1277583,-0.1277583,-1.8904010,-1.8904010),
                      n = c(3,3,3,2,2),
                      location = c('London', 'London', 'London', 'Birmingham', 'Birmingham'),
                      tweet = c('Great', 'I love this', 'like it', 'hate it', 'worst ever'))

m = leaflet(data_map) %>%
       setView(lng = -1.470085  , lat=53.38113,zoom=5) %>% 
       addTiles() %>%
       #addProviderTiles(providers$Stamen.Toner) %>% 
       addCircleMarkers( 
       lng = ~lon, 
       lat = ~lat,
       #popup = ~Location,
       #size=3,
       radius = ~n*3, 
       stroke = T, 
       fillOpacity = 0.5,
       popup=paste(
                   "Address:", data_map$location, "<br>",
                   "number of tweets:", df_map$n, "<br>",
                   "Posts:", data_map$tweet)
       )
print(m)

Upvotes: 3

Views: 1439

Answers (1)

Humpelstielzchen
Humpelstielzchen

Reputation: 6441

You could reduce your data to one row per location and save all the tweets per location in a list-column.

library(leaflet)
library(dplyr)
data_map = data.frame(lat=c(51.50735, 52.48624),
                      lon=c(-0.1277583,-1.8904010),
                      n = c(3,2),
                      location = c('London', 'Birmingham'))

data_map$tweets <- list(c('Great', 'I love this', 'like it'), c('hate it', 'worst ever'))

m = leaflet(data_map) %>%
  setView(lng = -1.470085  , lat=53.38113,zoom=5) %>% 
  addTiles() %>%
  #addProviderTiles(providers$Stamen.Toner) %>% 
  addCircleMarkers( 
    lng = ~lon, 
    lat = ~lat,
    #popup = ~Location,
    #size=3,
    radius = ~n*3, 
    stroke = T, 
    fillOpacity = 0.5,
    popup= ~paste(
      "<strong> Address: </strong>", location, "<br>",
      "<strong> number of tweets: </strong>", n, "<br>",
      "<strong> Posts: </strong>", "<br>", lapply(tweets, paste, collapse = "<br>")
    ))

m

enter image description here

Upvotes: 1

Related Questions