Inspired by Zev Ross’ fantastic series of blog posts, I decided to quickly try a bit of mapping of my own. This took literally five minutes and I have made no effort to make the map too attractive. I have not separated dots by any grouping variable (e.g. what league they are in) and I have shamelessly copied Zev’s css styling for the pop up windows when you hover over each dot. I basically just wanted to try out how dplyr, rvest and leaflet all work together. The answer is they do so very nicely.

 

I found a website that has all the locations (Latitude and Longitude) of all English, Welsh and Scottish professional soccer grounds, along with their names and capacities.

I notice that the information is actually kept in a very convenient table format, so using rvest I simply tell it to extract all information contained within <td> wrappers. That spits out five bits of information per team. - The team name, the ground name, the capcity, the latitude and longitude. I then just pop them in a dataframe.

 

library(rvest)
library(dplyr)
library(leaflet)

### Scrape Location Data
url<-html("http://www.doogal.co.uk/FootballStadiums.php")

selector_name<-"td"
deets <- html_nodes(url, selector_name) %>% html_text()
df <- as.data.frame(matrix(deets, ncol=5, byrow=T))
colnames(df)<-c("Stadium", "Team", "Capacity", "Lat", "Long")

head(df)
##              Stadium                     Team Capacity     Lat      Long
## 1      Abbey Stadium         Cambridge United   10,847 52.2128  0.154298
## 2         Adams Park        Wycombe Wanderers   10,284 51.6306 -0.800299
## 3 Almondvale Stadium               Livingston   10,122 55.8864  -3.52207
## 4       Amex Stadium Brighton and Hove Albion   22,374 50.8609  -0.08014
## 5            Anfield                Liverpool   45,522 53.4308  -2.96096
## 6        Ashton Gate             Bristol City   21,497   51.44  -2.62021

 

Next, let’s define the information I want to appear in the pop up - I’ve kept Zev’s css styling here as it’s very nice.

 

###pop-up
popInfo<-paste("<h4 style='border-bottom: thin dotted #43464C;
    padding-bottom:4px; margin-bottom:4px;
    font-family: Tahoma, Geneva, sans-serif;
    color:#43464C;'>", df$Team, "</h4>
    <span style='color:#9197A6;'>", df$Stadium, "<br>", df$Capacity, "<br>", "</span>", sep="")

 

Now let’s map it using leaflet!

### Map
leaflet(data=df, height="650px", width="100%") %>%
  addCircles(lat = ~ df$Lat, lng = ~ df$Lon, weight=3, opacity=1, fillOpacity=0.6, radius=500, popup = popInfo) %>%
  addTiles("http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png") %>%
  setView(-2.082444, 54.5, zoom=6) 

 

 

You should see a scrollable, zoomable map complete with blue dots indicating the location of each ground. Click on each dot to reveal the extra information.

It’s very straightforward and took no time at all.