how to integrate kml layers on top of leaflet data

I have a leaflet map that is plotting data and works as expected for me.

leaflet(demo_data) %>%
  addTiles() %>%
  addCircleMarkers(lng = ~lg, lat = ~lt, color = ~color, opacity = 1,
                   popup = ~sprintf("<h3><b>Vehicle No : %s</b></h3>", termid)) %>%
  leaflet::addLegend(
    position = 'bottomright',
    opacity = 1,
    color = ~unique(color),
    labels = ~unique(label),
    title = 'Color Range Chart'
  )

Now, I have another kml file that has additional data about the same coordinates. How do I plot information from kml file on top of already existing leaflet map?

I am reading kml file using sf package with st_read function

kml_data <- sf::st_read('data.kml')

I have searched extensively for this issue and try out various things with plotting sf data with leaflet, tried out rmaps, simplevis package but none of them works for me.

Any pointers?

PS - I am using this in a shiny application.

I am not 100% certain I follow the "on top of existing leaflet map" part.

In theory there should not be any problem with stacking several calls of addMarkers (or addCircleMarkers) on top of each other.

How exactly does it not work for you? Is it a {leaflet} issue or a general {sf} points geometry issue?

Stacking layers on layers is usually straightforward, such asthis:

library(sf)
library(dplyr)
library(leaflet)


shape <- st_read(system.file("shape/nc.shp", package="sf")) # included with sf package

cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),
                     x = c(-78.633333, -79.819444, -77.912222),
                     y = c(35.766667, 36.08, 34.223333),
                     population = c(467665, 299035, 115451)) %>% 
  st_as_sf(coords = c("x", "y", "population"), crs = 4326, dim = "XYZ")


leaflet() %>% 
  addTiles() %>% # genric OSM basemap
  addPolygons(data = shape) %>% # county polygons in blue
  addCircleMarkers(data = cities, color = "red") # 3 semi random cities in red

2 Likes

I think this would do it for me for now. I should have read the documentation more carefully. Thank you for your help.

Oki, glad to be of service!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.