Multiple markers on same coordinate

2019-03-19 05:49发布

问题:

When plotting out markers on a interactive worlmap from the r package leaflet data with exactly the same coordinates will overlap each other.

See the example below:

library(leaflet)

Data <- structure(list(Name = structure(1:3, .Label = c("M1", "M2", "M3"), class = "factor"), Latitude = c(52L, 52L, 51L), Longitude = c(50L, 50L, 50L), Altitude = c(97L, 97L, 108L)), .Names = c("Name", "Latitude", "Longitude", "Altitude"), class = "data.frame", row.names = c(NA, -3L))

leaflet(data = Data) %>% 
              addProviderTiles("Esri.WorldImagery", options = providerTileOptions(noWrap = TRUE)) %>%
              addMarkers(~Longitude, ~Latitude, popup = ~as.character(paste(sep = "",
                                                                          "<b>",Name,"</b>","<br/>", "Altitude: ",Altitude)))

There is a possibilty to show all coordinates with the cluster option, but this is far from my goal. I dont want clusters and only the overlapping Markers are shown when fully zoomed in. When fully zoomed in the background map turns into grey("Map data not yet available"). The spider view of the overlapping markers is what i want, but not when fully zoomed in.

See example below:

leaflet(data = Data) %>% 
  addProviderTiles("Esri.WorldImagery", options = providerTileOptions(noWrap = TRUE)) %>%
  addMarkers(~Longitude, ~Latitude, popup = ~as.character(paste(sep = "",
                                                                "<b>",Name,"</b>","<br/>", "Altitude: ",Altitude)), clusterOptions = markerClusterOptions())

I found some literatur about the solution i want but i dont know how to implement it in the r leaflet code/package. https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet

Also if there are other approaches to handle overlapping Markers, feel free to answer. (for example multiple Markers info in one popup)

回答1:

You could jitter() your coordinates slightly:

library(mapview)
library(sp)

Data <- structure(list(Name = structure(1:3, .Label = c("M1", "M2", "M3"), 
                                        class = "factor"), 
                       Latitude = c(52L, 52L, 51L), 
                       Longitude = c(50L, 50L, 50L), 
                       Altitude = c(97L, 97L, 108L)), 
                  .Names = c("Name", "Latitude", "Longitude", "Altitude"), 
                  class = "data.frame", row.names = c(NA, -3L))

Data$lat <- jitter(Data$Latitude, factor = 0.0001)
Data$lon <- jitter(Data$Longitude, factor = 0.0001)

coordinates(Data) <- ~ lon + lat
proj4string(Data) <- "+init=epsg:4326"

mapview(Data)

This way you still need to zoom in for the markers to separate, how far you need to zoom in depends on the factor attribute in jitter().

Note that I am using library(mapview) in the example for simplicity.



标签: r shiny leaflet