#################################################################################################
#RStudio

###################
#ggmap
###################
#call libraries
library(ggmap)
library(ggplot2)


#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

#import csv file. First change working directory
setwd("C:\\Rmaps")
#read csv
cities <- read.csv("Cities_R.csv")

#draw an empty simple map
m <- get_map(location = 'europe', maptype = "watercolor", source = "google", zoom = 4)
#display map
ggmap(m)

e <- get_map(location = 'europe', maptype = "toner-lite", source = "google", zoom = 4)
ggmap(e) + geom_point(aes(x = cities$Longitude, y = cities$Latitude), colour ="#0066FF" ,size = 4, data = cities) 
ggmap(e) + geom_point(aes(x = cities$Longitude, y = cities$Latitude, colour = factor(Country), size = Population), data = cities) 

###################
#subplot
###################
#call libraries
library(maps)
library(ggmap)
library(ggplot2)
library(dplyr)
library(TeachingDemos)
library(reshape2)
library(methods)
require(TeachingDemos)

#import csv file. First change working directory
setwd("C:\\Rmaps")
#read csv
sp <- read.csv("Cities_Italy_gender_R.csv")

tb <- sp
map('world', region = 'Italy')
points(tb$Longitude, tb$Latitude, col = "#0066FF", pch = 20, cex = 2)
for(i in 1:nrow(tb)){
  subplot(barplot(height = as.numeric(as.character(unlist(tb[i,6:7], use.names = FALSE ))), 
                  cex.names = 0.5, axes = FALSE, col=rainbow(8)),
          x = tb[i,'Longitude'], y = tb[i, 'Latitude'], size = c(0.3,0.3), vadj = 0
  )
}
legend("topright", legend=names(tb[, 6:7]), fill=rainbow(8), bty = "n", cex = 0.8)

###################
#routes
###################
#call libreries
library(maps)
library(dplyr) #for filtering data
library(calibrate) #for drawning lines on a map
library(geosphere) #for drawning lines on a map

#import csv file. First change working directory
setwd("C:\\Rmaps")
#read csv
cities <- read.csv("Cities_R.csv")

dataset <- cities

#draw european countries map
map('world', region = c('Austria', 'Belgium', 'Denmark','France','Germany','Netherlands','Hungary','Ireland','Italy','Poland','Portugal','Slovenia','Spain','Switzerland','UK'))
#filter origin
orig <- filter(dataset, City  == "COPENHAGEN")
dest <- filter(dataset, Country != "DENMARK") #esclude all destinations in Italy
#plot the origin
points(orig$Longitude, orig$Latitude, col = "#00cc00", pch = 19, cex = 3)
#plot the destinations
points(dest$Longitude, dest$Latitude, col = "#0066FF", pch = 19, cex = 3)
#plot the directions
for (i in 1:nrow(dest))
{
  a <- c(orig[1,]$Longitude, orig[1,]$Latitude)
  b <- c(dest[i,]$Longitude, dest[i,]$Latitude)
  #calls the function gcIntermediate to get intermediate points (way points) between the two locations with longitude/latitude coordinates.
  intermed <- gcIntermediate(a,b,n=100,addStartEnd=TRUE)
  lines(intermed, col="black", lwd=2)
}

###################
#shape map
###################
library(sf)
library(units)
library(rgdal)
library(ggplot2)
library(rgeos)
library(maptools)
library(dplyr)
library(scales)

#import shape file
setwd("C:/RMaps/EU_shape")
eu.shp <- readOGR(dsn = "C:/RMaps/Eu_shape", layer = "MyEurope") %>%
  spTransform(CRS("+init=epsg:4326"))
#import demo data
setwd("C:/RMaps")
eu.dt <- read.csv("Europe_shape_demo_data.csv",header = TRUE, sep = ';')
colnames(eu.dt)[1] <- "CountryCode"

#fortify shape file to get into dataframe 
eu.shp.f <- fortify(eu.shp, region = "GMI_CNTRY")
class(eu.shp.f) #to test the class of the object
#rename the id column to match the CountryCode from the other dataset
colnames(eu.shp.f)[6] <- "CountryCode"
#merge with CountryCodes
merge.shp <-merge(eu.shp.f, eu.dt, by="CountryCode", all.x=TRUE)
fp <-merge.shp[order(merge.shp$order), ] 
#delete countries that not match
final.plot <- filter(fp, TotalExpense != "NA")

#basic plot
ggplot()  + 
  geom_polygon(data = final.plot, aes(x = long, y = lat, group = group, fill =TotalExpense ), color = "black", size = 0.25) + 
  coord_map() + 
  scale_fill_distiller(name="Expenses", palette = "Oranges", breaks = pretty_breaks(n = 5))  + 
  labs(title = "Travel Expenses 2011 - 2017") + 
  theme(axis.line=element_blank(),
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_blank(),
        panel.border=element_blank(),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        plot.background=element_blank(),
        plot.title = element_text(hjust = 0.5)
  )

###############
#geocoding
###############
library(ggplot2)
library(ggmap)
library(dplyr)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

#import txt file. First change working directory
setwd("C:\\Rmaps")
#read txt
addr <- read.table("HotelAddress.txt", sep = "|", header = T)

#if necessary promote headers. Redundant if using instruction header = T
colnames(addr) <- as.character(unlist(addr[1,])) #promote headers
addr <- addr[-1,] #remove the first row from dataset

#concat columns for getting full address
full_addr <- paste(addr$Address, addr$City, addr$Country, sep = ",")
#geocode
gc <- geocode(as.character(full_addr), output = "latlon", source ="google")
m <- get_map(location = 'Europe', maptype = "roadmap", source = "google", zoom = 4)
ggmap(m) + geom_point(aes(x = lon, y = lat), colour ="#ff3300", size = 5 ,data = gc)  

###############
#map dist
###############
library(ggplot2)
library(ggmap)
library(dplyr)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

#import txt file. First change working directory
setwd("C:\\Rmaps")
#read txt
addr <- read.table("HotelAddress.txt", sep = "|", header = T)

#if necessary promote headers. Redundant if using instruction header = T
colnames(addr) <- as.character(unlist(addr[1,])) #promote headers
addr <- addr[-1,] #remove the first row from dataset

#concat columns for getting full address
full_addr <- paste(addr$Address, addr$City, addr$Country, sep = ",")
#geocode
gc <- geocode(as.character(full_addr), output = "latlon", source ="google")
m <- get_map(location = 'Europe', maptype = "roadmap", source = "google", zoom = 4)
ggmap(m) + geom_point(aes(x = lon, y = lat), colour ="#ff3300", size = 5 ,data = gc)  


#########################
#leaflet
#########################
#Interactive mapping with Leaflet in R
library(leaflet)
library(plotly)
#library(tidyverse)
library(ggplot2)
library(htmlwidgets)
#library(XML)
library(sp)
library(maps)
m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")
m  # Print the map


####################################################################################
#Power BI
###################
#ggmap
###################
#call libraries
library(ggmap)
library(ggplot2)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

e <- get_map(location = 'europe', maptype = "toner-lite", source = "google", zoom = 4)
ggmap(e) + geom_point(aes(x = dataset$Longitude, y = dataset$Latitude, colour = factor(Country), size = Population), data = dataset)

###################
#subplot
###################
#call libraries
library(maps)
library(ggmap)
library(ggplot2)
library(dplyr)
library(TeachingDemos)
library(reshape2)
library(methods)
require(TeachingDemos)

tb <- dataset
map('world', region = 'Italy')
points(tb$Longitude, tb$Latitude, col = "#0066FF", pch = 20, cex = 2)
for(i in 1:nrow(tb)){
  subplot(barplot(height = as.numeric(as.character(unlist(tb[i,3:4], use.names = FALSE ))), 
                  cex.names = 0.5, axes = FALSE, col=rainbow(8)),
          x = tb[i,'Longitude'], y = tb[i, 'Latitude'], size = c(0.3,0.3), vadj = 0
  )
}
legend("topright", legend=names(tb[, 3:4]), fill=rainbow(8), bty = "n", cex = 0.8)

###################
#routes
###################
#call libreries
library(maps)
library(dplyr) #for filtering data
library(calibrate) #for drawning lines on a map
library(geosphere) #for drawning lines on a map

#draw european countries map
map('world', region = c('Austria', 'Belgium', 'Denmark','France','Germany','Netherlands','Hungary','Ireland','Italy','Poland','Portugal','Slovenia','Spain','Switzerland','UK'))
#filter origin
orig <- filter(dataset, City  == "COPENHAGEN")
dest <- filter(dataset, City != "COPENHAGEN") #exclude origin
#plot the origin                                                                                                                                                                             
points(orig$Longitude, orig$Latitude, col = "#00cc00", pch = 19, cex = 3)                                                                                                                  
#plot the destinations
points(dest$Longitude, dest$Latitude, col = "#0066FF", pch = 19, cex = 3)
#plot the directions
for (i in 1:nrow(dest))
{
  a <- c(orig[1,]$Longitude, orig[1,]$Latitude)
  b <- c(dest[i,]$Longitude, dest[i,]$Latitude)
  #calls the function gcIntermediate to get intermediate points (way points) between the two locations with longitude/latitude coordinates.
  intermed <- gcIntermediate(a,b,n=100,addStartEnd=TRUE)
  lines(intermed, col="black", lwd=2)
}

###################
#shape map
###################
library(ggplot2)
library(dplyr)
library(scales)
library(RColorBrewer)
library(maptools)
library(plotly)
library(sf)
library(units)
library(rgdal)
library(ggplot2)
library(rgeos)
#import shape file
setwd("C:/RMaps/EU_shape")
eu.shp <- readOGR(dsn = "C:/RMaps/Eu_shape", layer = "MyEurope") %>%
  spTransform(CRS("+init=epsg:4326"))
#import demo data
setwd("C:/RMaps")
eu.dt <- read.csv("Europe_shape_demo_data.csv",header = TRUE, sep = ';')
colnames(eu.dt)[1] <- "CountryCode"

#fortify shape file to get into dataframe 
eu.shp.f <- fortify(eu.shp, region = "GMI_CNTRY")
#rename the id column to match the CountryCode from the other dataset
colnames(eu.shp.f)[6] <- "CountryCode"
#merge with CountryCodes
merge.shp <-merge(eu.shp.f, eu.dt, by="CountryCode", all.x=TRUE)
fp <-merge.shp[order(merge.shp$order), ] 
#delete countries that not match
final.plot <- filter(fp, TotalExpense != "NA")

#basic plot
ggplot()  + 
  geom_polygon(data = final.plot, aes(x = long, y = lat, group = group, fill =TotalExpense ), color = "black", size = 0.25) + 
  coord_map() + 
  scale_fill_distiller(name="Expenses", palette = "Oranges", breaks = pretty_breaks(n = 5))  + 
  labs(title = "Travel Expenses 2011 - 2017") + 
  theme(axis.line=element_blank(),
        axis.text.x=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks=element_blank(),
        axis.title.x=element_blank(),
        axis.title.y=element_blank(),
        panel.background=element_blank(),
        panel.border=element_blank(),
        panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        plot.background=element_blank(),
        plot.title = element_text(hjust = 0.5)
  )

###################
#geocode 1
###################
library(ggplot2)
library(ggmap)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

wh <- geocode("Ghelamco Arena, Ottergemsesteenweg Zuid, Gent, Belgium", output = "latlon", source ="google")
qmap(location = c(lon = wh$lon, lat = wh$lat), zoom = 15, maptype = "satellite")

###################
#geocode
###################
library(ggplot2)
library(ggmap)
library(dplyr)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

addr <- filter(dataset, City  == "Paris")
gc <- geocode(as.character(addr$FullAddress), output = "latlon", source ="google")
m <- get_map(location = 'Paris', maptype = "roadmap", source = "google", zoom = 11)
ggmap(m) + geom_point(aes(x = lon, y = lat), colour ="#ff3300", size = 5 ,data = gc)  + geom_text(x = gc$lon, y = gc$lat, label = paste(addr$Hotel, gc$lat, gc$lon, sep = "-"), size = 5, hjust = 0, vjust = 0.5, angle = 10)

###################
#mapdist 1
###################
#call libraries
library(ggmap)
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

from <- "Copenhagen"
to <- "Amsterdam"

dca <- mapdist(from, to, mode = "driving")
dca.df <- data.frame(dca)
grid.table(dca.df)

###################
#map dist2
###################
#call libraries
library(ggmap)
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)

#register your google key
register_google(key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

from <- "Copenhagen"
to <- "Amsterdam"

#routing
route_df <- route(from, to, structure = 'route', mode = 'driving')
m <- get_map(location = 'Europe', maptype = "roadmap", source = "google", zoom = 5)
ggmap(m) +
  geom_path(aes(x = lon, y = lat),  colour = 'blue', size = 1.5,data = route_df, lineend = 'round')
