3
votes

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.

1
we can't test your code, but maybe you could start by adding a color argument in your addPolygons() expression ; (color = ~colorQuantile(...) - MLavoie
Yes I already tried this and now updated the above code as well. Still the same problem. :( - Amir
MLavoie can it be because of the latitude and longitude in my SPDF, they are without the decimal points as I imported data from OSM? - Amir
it's possible but without having access to your dataset it's hard to know - MLavoie
You can find my SPDF at this link: filedropper.com/showdownload.php/spdf - Amir

1 Answers

5
votes

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.