require(knitr)

opts_chunk$set(
  cache = TRUE,
  error = TRUE,
  message = FALSE,
  warning = FALSE
)
require(dplyr)
require(sp) # Manipulação de Objetos Espaciais
require(rgdal) # Leitura de Objetos Espaciais
require(ggplot2)
require(ggthemes) 
require(RColorBrewer) # Manipulação de Cores
# Mapas Interativos
require(leaflet) 
require(leaflet.extras)
require(mapview)
cwb_imovel <-
  rgdal::readOGR(
    dsn = "/home/gabriel/Suporte/DataScience/Estatistica/Eventos/Rbras_2018/R_Day/aula/bairro_m2", 
        layer = "OGRGeoJSON",
    verbose = FALSE)

plot(cwb_imovel)

# Removendo o prefixo Regional
cwb_imovel$nome_regional <- gsub("REGIONAL ", "", cwb_imovel$nome_regional)

# Unir os polígonos dos bairros com as regionais
regional <- maptools::unionSpatialPolygons(cwb_imovel, cwb_imovel$nome_regional)
plot(regional)

class(regional)
## [1] "SpatialPolygons"
## attr(,"package")
## [1] "sp"
# Convertendo objeto Espacial p/ Objeto Espacial Data Frame
df_reg <- data.frame(reg = names(regional))
rownames(df_reg) <- names(regional)

spdf_regional <- SpatialPolygonsDataFrame(regional, df_reg)
class(spdf_regional)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"
slotNames(spdf_regional)
## [1] "data"        "polygons"    "plotOrder"   "bbox"        "proj4string"

Mapview Popup Imagem

# ADD Imagem 
imagens <- list.files(path = "./Image", pattern = ".jpg|.jpeg")
arq <- ""
pop_ima <- mget(rep("arq", length(spdf_regional))) # replicar o Objeto
pop_ima <- lapply(1:length(pop_ima), function(i) {
  paste0("/home/gabriel/Suporte/DataScience/Estatistica/Eventos/Rbras_2018/R_Day/Image/",imagens)[i]
})
mapview(spdf_regional,
        col.regions = RColorBrewer::brewer.pal(n = 10, name = "Paired"),
        legend = TRUE,
        layer.name = "Regional",
        map.types = c("OpenStreetMap.BlackAndWhite"),
        alpha.regions = 1,
        popup = popupImage(pop_ima, src = c("local")),
        label = spdf_regional$reg)

Leaflet Camadas

# Paleta de Cores
# Base de Dados de Qualidade da Água no Paraná
pasta <- "/home/gabriel/Suporte/TCC/02 - Projeto A. E. E. nº 001-2016 - Índice de Qualidade das Águas/Banco de dados/IQA_PR_atualizado_Setembro_2013/Preparação dos dados/"

file_iqa <- paste0(pasta, "iqa_parana.csv")

nd.agua <- read.csv(file_iqa, header = TRUE, sep = ",",
                    fileEncoding = "utf8",
                    na.strings = "NA", stringsAsFactors = TRUE,
                    # setando formato das variáveis
                    colClasses =
                      c(rep("factor", 9), "numeric", "numeric", "Date", "character", "integer",  
                        "character", rep("numeric", 6), "integer", "numeric", "integer", "integer",                             "numeric", "numeric", "numeric", "numeric", "integer", rep("numeric", 3), 
                        "integer", "numeric",  rep("factor", 10), rep("numeric", 25), 
                        "character", "character"
                      )
)
class(nd.agua)
## [1] "data.frame"
# Converter lat/long em Spatial Points Data.frame

nd.agua$long <- as.numeric(as.character(nd.agua$long))
nd.agua$lat <- as.numeric(as.character(nd.agua$lat))

monit <- nd.agua %>%
  dplyr::select(long, lat, estac, calc_iqa, season, munic) %>%
  na.omit()

monit_media <- monit %>%
  group_by(long, lat, estac) %>% 
  summarise(iqa = mean(calc_iqa, na.rm = TRUE)) %>% 
  na.omit()

# Somente os Pontos de Monitoramento de CWB

cwb_iqa <- monit %>% 
  filter(munic == "Curitiba") %>% 
  group_by(estac) %>% 
  summarise(lat = unique(lat),
            long = unique(long), 
            iqa = mean(calc_iqa)) %>% 
  droplevels()

class(cwb_iqa)
## [1] "tbl_df"     "tbl"        "data.frame"
head(cwb_iqa, 6)
## # A tibble: 6 x 4
##   estac                                             lat  long   iqa
##   <fct>                                           <dbl> <dbl> <dbl>
## 1 65007010 - AI55 - JUSANTE CÓRREGO MONJOLO       -25.4 -49.2  42.0
## 2 65007020 - AI62 - PARQUE BACACHERI              -25.4 -49.2  41.2
## 3 65007022 - AI34 - JUSANTE FRIGORÍFICO BACACHERI -25.4 -49.2  58.7
## 4 65007030 - AI63 - JUSANTE DA BR 116             -25.4 -49.2  40.5
## 5 65011000 - AI56 - MONTANTE PARQUE SÃO LOURENÇO  -25.4 -49.3  42.4
## 6 65011200 - AI65 - FOZ DO RIO IVO                -25.4 -49.3  19.0
# Convertendo dados
sp::coordinates(cwb_iqa) <- ~long+lat
class(cwb_iqa)
## [1] "SpatialPointsDataFrame"
## attr(,"package")
## [1] "sp"

LeafLet Camadas

# Paleta de Cores da Qualidade da Água
palet_iqa <- colorBin("RdYlGn", cwb_iqa$iqa, bins = c(0,25,50,70,90,100))

# Paleta de Cores Bairros
cwb_imovel$m2_ap <- round(cwb_imovel$m2_ap)
breaks_equal <- classInt::classIntervals(cwb_imovel$m2_ap, 
                                         n = 5, style = "equal",
                                         dataPrecision = 1)

palet_leaf <- colorBin("Oranges", cwb_imovel$m2_ap, bins = breaks_equal$brks)

# Popups M2 Bairro
popups <- paste0("<strong> Preço M2 : </strong>", 
                round(cwb_imovel$m2_ap, 2),
                "<br> <strong> Bairro : </strong>",
                cwb_imovel$nome)


leaflet(cwb_imovel) %>% 
  addProviderTiles(providers$OpenStreetMap.DE) %>%  # Base Map
  addPolygons(color = "black", # Polígonos
              fillColor = ~palet_leaf(cwb_imovel$m2_ap), # Variável de Interesse
              weight = 1,
              fillOpacity = 1,
              label = ~nome,
              popup = popups,
              group = "M2") %>% # Grupo
  addLegend(pal = palet_leaf, value = ~m2_ap, # Legenda
            opacity = 1, title = "M2 de AP",
            group = "M2") %>% 
  addCircleMarkers(data = cwb_iqa,
                   fillColor = ~palet_iqa(iqa),
                   color = "black", 
                   opacity = 1,
                   fillOpacity = 1,
                   radius = 5,
                   weight = 1,
                   stroke = TRUE,
                   group = "IQA",
                   label = ~iqa) %>% 
  addLegend(pal = palet_iqa,
            value = palet_iqa(cwb_iqa$iqa),
            opacity = 1,
            title = "IQA",
            group = "IQA"
  ) %>% 
  addProviderTiles(providers$OpenStreetMap.DE, group = "StreetMap", "Hydda_Full") %>% 
  addProviderTiles(providers$Hydda.Full, group = "Hydda_Full") %>% 
  addLayersControl( 
    overlayGroups = c("M2", "IQA"),
    baseGroups = c("StreetMap", "Hydda_Full")
  )