library(SDMTools)
library(igraph)
## 
## Attaching package: 'igraph'
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
library(leaflet)
library(geosphere)

# *****************************************************************************
#                       R Script For Center Clustering
# *****************************************************************************

# clears all objects in "global environment"
rm(list=ls())

# latitude and lontitude is referenced from https://www.latlong.net/
# calculate center of first clusters
lonlat1 <- read.table(textConnection( "lon, lat 
                                     9.993682,53.551086 
                                     -0.127758,51.507351
                                     19.455982,51.759247
                                     4.477733,51.924419
                                     4.402464,51.219448
                                     11.974560,57.708870 
                                     "),header=TRUE,strip.white = TRUE, sep=",")

nname1 <- c("Hamburg","London","Lodz",
            "Rotterdam","Antwerp","Gothenburg")

v1 <- data.frame( ids = 1:6, 
                 name = nname1, 
                 x = lonlat1$lon, 
                 y = lonlat1$lat) 

centre1 <- COGravity(v1$x,v1$y)

leaflet(data=v1[1:6,]) %>% addTiles() %>%
  addMarkers(lng=v1$x, lat=v1$y, popup=v1$name) %>%
  addAwesomeMarkers(lng=centre1[1], lat=centre1[3], 
             icon = awesomeIcons(markerColor = "red"),
             popup="center of cluster 1")
print(paste("Center of Cluster 1 is at longitude = ", centre1[1],
            "and latitude = ", centre1[3]))
## [1] "Center of Cluster 1 is at longitude =  8.36277716666667 and latitude =  52.9450701666667"
################################################################################

# calculate center of second clusters
lonlat2 <- read.table(textConnection( "lon, lat 
                                      9.189982,45.464203 
                                      5.369780,43.296482
                                      2.173404,41.385063
                                      "),header=TRUE,strip.white = TRUE, sep=",")

nname2 <- c("Milan","Marseille","Barcelona")

v2 <- data.frame( ids = 1:3, 
                  name = nname2, 
                  x = lonlat2$lon, 
                  y = lonlat2$lat) 

centre2 <- COGravity(v2$x,v2$y)

leaflet(data=v2[1:3,]) %>% addTiles() %>%
  addMarkers(lng=v2$x, lat=v2$y, popup=v2$name) %>%
  addAwesomeMarkers(lng=centre2[1], lat=centre2[3], 
                    icon = awesomeIcons(markerColor = "red"),
                    popup="center of cluster 2")
print(paste("Center of Cluster 2 is at longitude = ", centre2[1],
            "and latitude = ", centre2[3]))
## [1] "Center of Cluster 2 is at longitude =  5.577722 and latitude =  43.381916"
print("End of cluster defined")
## [1] "End of cluster defined"