import csv, requests

url = "https://aql.datapress.com/leeds/dataset/wards-in-leeds/wardsgeoarea.csv"
response = requests.get(url)

import io

file = io.StringIO(response.content.decode("utf8"))

reader = csv.reader(file)
next(reader)

import collections

Ward = collections.namedtuple("Ward", ["code", "name", "url"])
wards = [Ward(*row) for row in reader]
wards[0]    

"""
Explanation: Case study: electoral wards in Leeds
Getting hold of the wards in Leeds seems tricky, and requires joining two datasets and some HTTP work.  Makes it fun, I guess.
We start from data from Leeds city council.  But this only gives links to the shapefiles.
Wards in Leeds, (c) Leeds City Council, 2014, https://datamillnorth.org/dataset/wards-in-leeds.  This information is licensed under the terms of the Open Government Licence.
End of explanation
"""


import json

url = "http://statistics.data.gov.uk/boundaries/{}.json"
shapes = dict()
for ward in wards:
    response = requests.get(url.format(ward.code))
    shapes[ward.code] = json.loads(response.content.decode("utf8"))

"""
Explanation: Grab ONS data
We now need to follow each URL.  This data:

Contains National Statistics data © Crown copyright and database right [year]
Contains OS data © Crown copyright and database right [year]

See https://www.ons.gov.uk/methodology/geography/licences
End of explanation
"""


import geopandas as gpd

frame = gpd.GeoDataFrame.from_features(shapes.values())
frame.head()

"""
Explanation: Load into geoPandas
End of explanation
"""


%matplotlib inline
import matplotlib.pyplot as plt

frame.plot()

# Set projection as lon/lat, then reproject to "web mercator"
frame.crs = {"init": "EPSG:4326"}
frame = frame.to_crs({"init": "EPSG:3857"})

import tilemapbase

fig, ax = plt.subplots(figsize=(10,10))

extent = tilemapbase.extent_from_frame(frame, buffer=5)
plotter = tilemapbase.Plotter(extent, tilemapbase.tiles.OSM, width=600)
plotter.plot(ax)
frame.plot(ax=ax, column="WD15NM", categorical=True, alpha=0.2)
None

"""
Explanation: Plot
End of explanation
"""


