加入彈出視窗並儲存地圖
為了讓地圖更有資訊量,可以加入彈出視窗(popup)。若要在點選標記時顯示彈出視窗,需要在 addMarkers() 函式中指定 popup 參數。一旦有想保留的地圖,就可以把它儲存在一個物件中。之後再把這個物件透過管線傳給其他函式,來新增或編輯地圖的圖層。
dc_nyc <-
leaflet() %>%
addTiles() %>%
addMarkers(lng = -73.98575, lat = 40.74856,
popup = "DataCamp - NYC")
dc_nyc %>%
setView(lng = -73.98575, lat = 40.74856,
zoom = 2)
現在試著為兩個 DataCamp 地點的標記都加入彈出視窗,並把地圖儲存到一個物件中。
本練習屬於課程
在 R 中使用 leaflet 製作互動式地圖
練習說明
- 在
addMarkers()中加入popup參數,以顯示 hq 欄位的值,並將這個leaflet地圖儲存到名為map的物件。 - 將
map的視圖置中到比利時總部,縮放等級設為 5,並將結果儲存到map_zoom。 - 印出
map_zoom物件。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Store leaflet hq map in an object called map
___ <- leaflet() %>%
addProviderTiles("CartoDB") %>%
# Use dc_hq to add the hq column as popups
addMarkers(lng = dc_hq$lon, lat = dc_hq$lat,
popup = ___$___)
# Center the view of map on the Belgium HQ with a zoom of 5
map_zoom <- ___ %>%
setView(lat = 50.881363, lng = 4.717863,
zoom = ___)
# Print map_zoom
___