| 1 |
|
| 2 |
import csv |
| 3 |
import pathlib |
| 4 |
import random |
| 5 |
|
| 6 |
import shapefile |
| 7 |
from pygeoif.factories import force_3d |
| 8 |
from pygeoif.factories import shape |
| 9 |
|
| 10 |
import fastkml |
| 11 |
import fastkml.containers |
| 12 |
import fastkml.features |
| 13 |
import fastkml.styles |
| 14 |
from fastkml.enums import AltitudeMode |
| 15 |
from fastkml.enums import ColorMode |
| 16 |
from fastkml.geometry import create_kml_geometry |
| 17 |
|
| 18 |
examples_dir = pathlib.Path(__file__).parent |
| 19 |
|
| 20 |
shp = shapefile.Reader(examples_dir / "ne_110m_admin_0_countries.shp") |
| 21 |
|
| 22 |
co2_csv = pathlib.Path(examples_dir / "owid-co2-data.csv") |
| 23 |
|
| 24 |
co2_data = {} |
| 25 |
|
| 26 |
with co2_csv.open() as csvfile: |
| 27 |
reader = csv.DictReader(csvfile) |
| 28 |
for row in reader: |
| 29 |
if row["year"] == "2020": |
| 30 |
co2_data[row["iso_code"]] = ( |
| 31 |
float(row["co2_per_capita"]) if row["co2_per_capita"] else 0 |
| 32 |
) |
| 33 |
|
| 34 |
document = fastkml.containers.Document() |
| 35 |
|
| 36 |
for feature in shp.__geo_interface__["features"]: |
| 37 |
geometry = shape(feature["geometry"]) |
| 38 |
co2_emission = co2_data.get(feature["properties"]["ADM0_ISO"], 0) |
| 39 |
geometry = force_3d(geometry, co2_emission * 100_000) |
| 40 |
kml_geometry = create_kml_geometry( |
| 41 |
geometry, |
| 42 |
extrude=True, |
| 43 |
altitude_mode=AltitudeMode.relative_to_ground, |
| 44 |
) |
| 45 |
color = random.randint(0, 0xFFFFFF) |
| 46 |
style = fastkml.styles.Style( |
| 47 |
id=feature["properties"]["ADM0_ISO"], |
| 48 |
styles=[ |
| 49 |
fastkml.styles.LineStyle(color=f"55{color:06X}", width=2), |
| 50 |
fastkml.styles.PolyStyle( |
| 51 |
color_mode=ColorMode.random, |
| 52 |
color=f"88{color:06X}", |
| 53 |
fill=True, |
| 54 |
outline=True, |
| 55 |
), |
| 56 |
], |
| 57 |
) |
| 58 |
|
| 59 |
style_url = fastkml.styles.StyleUrl(url=f"#{feature['properties']['ADM0_ISO']}") |
| 60 |
placemark = fastkml.features.Placemark( |
| 61 |
name=feature["properties"]["NAME"], |
| 62 |
description=feature["properties"]["FORMAL_EN"], |
| 63 |
kml_geometry=kml_geometry, |
| 64 |
styles=[style], |
| 65 |
) |
| 66 |
document.append(placemark) |
| 67 |
|
| 68 |
kml = fastkml.KML(features=[document]) |
| 69 |
|
| 70 |
outfile = pathlib.Path("co2_per_capita_2020.kml") |
| 71 |
kml.write(outfile, prettyprint=True, precision=3) |