Union of circles and polygon in leaflet

后端 未结 2 801
囚心锁ツ
囚心锁ツ 2021-01-27 01:54

I am adding two circles and a polygon to a leaflet map. Here\'s my code which plots these three shapes. Is there any way I can get a union of these three shapes?



        
2条回答
  •  甜味超标
    2021-01-27 02:16

    As far as I know you can't. Whenever you add something on a leaflet map its considered as a separate layer, with separate properties and data:

    • The idea is to be able to hide/show those layers using interactive legends (so you want to keep your layers separated)
    • I don't see any simple way to access each circle's points' coordinates

    If you want to display something that's composed of several shapes, you'll have to create a complex SpatialPolygon yourself with points coordinates, sp package and this kind of code:

    require(sp)
    require(leaflet)
    
    #Used for sp polygon creation
    createPolygon <- function(latitude, longitude, name = "polygon"){
    
      return(Polygons(list(Polygon(cbind(longitude, latitude))), ID = name))
    
    }
    
    #Will give "res" points coordinates for a circle centered on x0 y0
    #with a radius r
    CreateCircle <- function(x0, y0, r, res = 50){
    
      theta = seq(0, 2*pi, length.out = res+1)
    
      x = r*cos(theta) + x0
      y = r*sin(theta) + y0
    
      return(data.frame(x, y))
    
    }
    
    #Computes two circles points'
    circleA <- CreateCircle (0, 0, 2, res = 200)
    circleB <- CreateCircle (10, 10, 4, res = 6)
    
    #Add them to polygons
    A = createPolygon(circleA$x, circleA$y, "A")
    B = createPolygon(circleB$x, circleB$y, "B")
    C = SpatialPolygons(list(A, B))
    
    #Create and display the leaflet map
    m = leaflet() %>% addTiles() %>%
      addPolygons(data = C, fillColor = topo.colors(10, alpha = NULL), stroke = TRUE)
    m
    

    If it can't display the result you want (e.g. because you want the circles to have different colors than your rectangles), you will have to use several layers and group them.

提交回复
热议问题