Boombardeiro
Boombardeiro

Reputation: 125

Misalignment of R polygon in leaflet map

When creating a leaflet map from R with providertiles the resulting .htmlfile does show a significant misalignment between the polygon (here country borders) and the basemap. Country borders for Switzerland were taken from here and are projected to EPSG4326. However, the result as shown in the screenshot below (lake Zurich) demonstrates the spatial difference. I am aware of this question and also of this hint but they didn't help me any further.

Here is a reproducible example:

#set working directory as desired----
wd <- setwd()

#download and unzip shapefile from URL----
temp <- tempfile()
download.file("https://geodata.ucdavis.edu/gadm/gadm4.0/shp/gadm40_CHE_shp.zip",temp)
unzip(temp, list=TRUE)
unzip(temp, "gadm40_CHE_0.cpg")
unzip(temp, "gadm40_CHE_0.dbf")
unzip(temp, "gadm40_CHE_0.prj")
unzip(temp, "gadm40_CHE_0.shp")
unzip(temp, "gadm40_CHE_0.shx")
unzip(temp, "gadm40_CHE_1.cpg")
unzip(temp, "gadm40_CHE_1.dbf")
unzip(temp, "gadm40_CHE_1.prj")
unzip(temp, "gadm40_CHE_1.shp")
unzip(temp, "gadm40_CHE_1.shx")
unlink(temp)

#load polygon (shapefile) as SF----
CH0 <-  sf::st_read(wd, layer="gadm40_CHE_0", stringsAsFactors = F)
sf::st_crs(CH0)
CH1 <-  sf::st_read(wd, layer="gadm40_CHE_1", stringsAsFactors = F)
sf::st_crs(CH1)

#leaflet----
library(dplyr) #for pipes
library(leaflet)
map <- leaflet() %>% 
          addProviderTiles(providers$Esri.WorldTopoMap) %>%
          
          addPolygons(data=CH1, color = "red", weight = 2, smoothFactor = 0.5, opacity = 0.75,
                      fillOpacity = 0.25, fillColor = "transparent", label = CH1$NAME_1) %>%
          addPolygons(data=CH0, color = "purple", weight = 2.5, smoothFactor = 0.5, opacity = 0.75,
                      fillOpacity = 0.25, fillColor = "transparent") %>%
          addMarkers(lng = 8.808369980330726, lat = 47.21968417926996) %>% 

          htmlwidgets::onRender("function() { 
                                    var map = this;
                                    var legends = map.controls._controlsById;
                                    function addActualLegend() {
                                       var sel = $('.leaflet-control-layers-base').find('input[type=\"radio\"]:checked').siblings('span').text().trim();
                                       $.each(map.controls._controlsById, (nm) => map.removeControl(map.controls.get(nm)));
                                       map.addControl(legends[sel]);
                                    }
                                    $('.leaflet-control-layers-base').on('click', addActualLegend);
                                    addActualLegend();
                                 }")
map

Screenshot of result

Upvotes: 1

Views: 182

Answers (0)

Related Questions