简体   繁体   English

如何使用R在传单上绘制多边形?

[英]How to plot polygons on leaflet using R?

I have a simple problem that I am facing while in try to plot a SpatialPolygonsDataFrame on top of Leaflet using R. My code is as below: 在尝试使用R在Leaflet顶部绘制SpatialPolygonsDataFrame时遇到一个简单的问题。我的代码如下:

leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    setView(lng = -80.8858673, lat = 41.1450276, zoom = 5) %>%
    addPolygons(data = SPDF, weight = 2, color = ~colorQuantile("red", SPDF$id)(id))

Where SPDF is my SpatialPolygonsDataFrame. 其中SPDF是我的SpatialPolygonsDataFrame。

When I execute this code it "PLOTS NOTHING" but only the base map. 当我执行此代码时,它“ PLOTS NOTHING”,但只有底图。 I have been searching around and this question is similar but it doesn't have this issue. 我一直在搜索,这个问题很相似,但是没有这个问题。

In order to plot the polygons I have been following this link. 为了绘制多边形,我一直关注链接。

The problem seems to be simple but it has consumed allot of time for me. 这个问题似乎很简单,但是却为我浪费了时间。 Looking forward for the suggestions. 期待提出建议。 Thanks for the time. 感谢您的时间。

NOTE: SPDF contains data exported from OSM, which means the coordinates (of POLYGONS) are without the decimal points as it is in the OSM data. 注意:SPDF包含从OSM导出的数据,这意味着(多边形)的坐标没有OSM数据中的小数点。

Finally, I have been able to figure out the problem myself. 最后,我自己能够解决问题。 The problem is in projections and the CRS (Coordinate Reference System) . 问题出在投影CRS(坐标参考系统)中

Default proj4string was not properly set at the first place and in result of which the coordinates were not realistic (without the decimal point). 默认的proj4string设置不正确,因此坐标不真实(无小数点)。 Therefore, first I set the default proj4string of my SpatialPolygonsDataFrame(SPDF): 因此,首先,我设置了SpatialPolygonsDataFrame(SPDF)的默认proj4string:

SPDF@proj4string <-CRS("+init=epsg:3857")

After setting this I provided the projection as following: 设置此设置后,我提供了如下投影:

SPDF <- spTransform(SPDF,  CRS("+ellps=WGS84 +proj=longlat +datum=WGS84 +no_defs"))

And now when I execute the following leaflet lines of code, it works perfectly. 现在,当我执行以下代码传单行时,它可以完美运行。

leaflet() %>%
    addProviderTiles("CartoDB.Positron") %>%
    setView(lng = -80.8858673, lat = 41.1450276, zoom = 5) %>%
    addPolygons(data = SPDF, weight = 2, color = ~colorQuantile("red", SPDF$osm_id)(osm_id))

In order to solve this I followed the discussion on this page. 为了解决这个问题我也跟着上讨论页。

I hope this works for others who are facing the same problem. 我希望这对面临相同问题的其他人也有用。 Though still I am not an expert of projections and cartography, therefore, it would be great if someone may recommend some necessary information to understand such issues. 尽管我仍然不是投影和制图专家,但是,如果有人可以推荐一些必要的信息来理解此类问题,那将是很好的。 Thanks all for the time. 感谢所有的时间。

PS: Make sure you have included the necessary packages such as leaflet, sp, magrittr etc. PS:请确保已包含必要的软件包,例如传单,sp,magrittr等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM