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:
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.
When I execute this code it "PLOTS NOTHING" but only the base map. 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.
Finally, I have been able to figure out the problem myself. The problem is in projections and the CRS (Coordinate Reference System) .
Default proj4string was not properly set at the first place and in result of which the coordinates were not realistic (without the decimal point). Therefore, first I set the default proj4string of my SpatialPolygonsDataFrame(SPDF):
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.