如何在传单(R)中的多边形的顶部y轴上添加标签?

时间:2019-08-13 12:56:16

标签: r shiny leaflet rstudio rgeo-shapefile

我想在传单的图层的多边形顶部添加标签。我需要它们靠近多边形的顶部(y轴),因为当启用该层上其他层的视图(带有最小的框)时,不应隐藏它们。

this example为参考,我使用gCentroid函数获取了多边形的质心(带有rgeos包),并尝试了方向=“ top”的传单“ addLabelOnlyMarkers”。 我也尝试在rgeos中使用其他一些功能(gBoundary gConvexHull gEnvelope gPointOnSurface),但是我什么也没找到。

#--Dummy data for the reproducible example--#

#1. Loading required libraries
library(rgeos)
library(leaflet) 

#2. Setting up the polygon
polygonX = readWKT(paste("GEOMETRYCOLLECTION(POLYGON((0 0,10 0,10 10,0 10,0 0)),",
 "POLYGON((15 0,25 15,35 0,15 0)))"))

#3.- Getting the centroid of the polygon/s (in this case one, but in my real example they are several) 
centers1 <- data.frame(gCentroid(polygonX , byid = TRUE))

#4.Adding the labels
l1 <- leaflet() %>%
     addPolygons(data = polygonX , 
              stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
              fillColor = "grey")  %>%  
     addLabelOnlyMarkers(data = centers1, 
                      lng = ~x, lat = ~y, label = ~x,
                      labelOptions = labelOptions(noHide = TRUE, direction = 'top', textOnly = TRUE)) 

此代码提供了形心上方的信息,而我需要在多边形的上边界下方。

LabelsCentered

-----更新-------

实际上,我已经能够做一些相对粗糙的事情,但是它正在挖掘多边形对象“ x”,并从y列坐标中获取最大值。


#---- modification (replacing the column in centers, with the max point in the top boundary of the polygon

arrayTopPolygon1 <- sapply(seq(1,length(polygonX@polygons)), function(i) {return(max(x@polygons[[i]]@Polygons[[1]]@labpt[,2]))}) #in my real example is coords[,2]
centers1 <- data.frame(gCentroid(polygonX , byid = TRUE))
centers1$y <- arrayTopPolygon1

#----

#4.Adding the labels
l1 <- leaflet() %>%
     addPolygons(data = polygonX , 
              stroke = FALSE, smoothFactor = 0.2, fillOpacity = 0.3,
              fillColor = "grey")  %>%  
     addLabelOnlyMarkers(data = centers1, 
                      lng = ~x, lat = ~y, label = ~x,
                      labelOptions = labelOptions(noHide = TRUE, direction = 'bottom', textOnly = TRUE)) 

到目前为止,这是结果,但也许可以改进: solution1_labelontoppolygon

0 个答案:

没有答案
相关问题