Debian Codegraph @

docs/create_kml_files.rst

raw
1 Creating KML files
2 ==================
3
4 Read a shapefile and build a 3D KML visualization.
5 --------------------------------------------------
6
7 This example shows how to read a shapefile and build a 3D KML visualization from it.
8
9 .. image:: co2-per-capita-2020.jpg
10 :alt: CO2 emissions per capita in 2020
11 :align: center
12 :width: 800px
13 :target: https://ion.cesium.com/stories/viewer/?id=a3cf93bb-bbb8-488b-8643-09c037ec12b8
14
15 (click on the image to see the KML visualization in Cesium Ion)
16
17 You will need to install `pyshp <https://pypi.org/project/pyshp/>`_ (``pip install pyshp``).
18
19 For this example we will use the
20 `Data on CO2 and Greenhouse Gas Emissions <https://github.com/owid/co2-data>`_ by
21 Our World in Data, and the Small scale data (1:110m) shapefile from
22 `Natural Earth <https://www.naturalearthdata.com/downloads/>`_.
23
24 First we import the necessary modules:
25
26 .. code-block:: pycon
27
28 >>> import csv
29 >>> import pathlib
30 >>> import random
31 >>> import shapefile
32 >>> from pygeoif.factories import force_3d
33 >>> from pygeoif.factories import shape
34 >>> import fastkml
35 >>> import fastkml.containers
36 >>> import fastkml.features
37 >>> import fastkml.styles
38 >>> from fastkml.enums import AltitudeMode
39 >>> from fastkml.geometry import create_kml_geometry
40
41
42 Read the shapefile:
43
44 .. code-block:: pycon
45
46 >>> shp = shapefile.Reader("examples/ne_110m_admin_0_countries.shp")
47
48 Read the CSV file and store the CO2 data for 2020:
49
50 .. code-block:: pycon
51
52 >>> shp = shapefile.Reader("examples/ne_110m_admin_0_countries.shp")
53 >>> co2_csv = pathlib.Path("examples/owid-co2-data.csv")
54 >>> co2_data = {}
55 >>> with co2_csv.open() as csvfile:
56 ... reader = csv.DictReader(csvfile)
57 ... for row in reader:
58 ... if row["year"] == "2020":
59 ... co2_data[row["iso_code"]] = (
60 ... float(row["co2_per_capita"]) if row["co2_per_capita"] else 0
61 ... )
62 ...
63
64
65 We prepare the styles and placemarks for the KML file, using random colors for each
66 country and the CO2 emissions as the height of the geometry. The shapefile offers
67 a handy ``__geo_interface__`` attribute that we can use to iterate over the features,
68 just like we would with a ``GeoJSON`` object, and extract the necessary information:
69
70 .. code-block:: pycon
71
72 >>> placemarks = []
73 >>> for feature in shp.__geo_interface__["features"]:
74 ... iso3_code = feature["properties"]["ADM0_A3"]
75 ... geometry = shape(feature["geometry"])
76 ... co2_emission = co2_data.get(iso3_code, 0)
77 ... geometry = force_3d(geometry, co2_emission * 100_000)
78 ... kml_geometry = create_kml_geometry(
79 ... geometry,
80 ... extrude=True,
81 ... altitude_mode=AltitudeMode.relative_to_ground,
82 ... )
83 ... color = random.randint(0, 0xFFFFFF)
84 ... style = fastkml.styles.Style(
85 ... id=iso3_code,
86 ... styles=[
87 ... fastkml.styles.LineStyle(color=f"33{color:06X}", width=2),
88 ... fastkml.styles.PolyStyle(
89 ... color=f"88{color:06X}",
90 ... fill=True,
91 ... outline=True,
92 ... ),
93 ... ],
94 ... )
95 ... placemark = fastkml.features.Placemark(
96 ... name=feature["properties"]["NAME"],
97 ... description=feature["properties"]["FORMAL_EN"],
98 ... kml_geometry=kml_geometry,
99 ... styles=[style],
100 ... )
101 ... placemarks.append(placemark)
102 ...
103
104
105 Finally, we create the KML object and write it to a file:
106
107 .. code-block:: pycon
108
109 >>> document = fastkml.containers.Document(features=placemarks)
110 >>> kml = fastkml.KML(features=[document])
111 >>> outfile = pathlib.Path("co2_per_capita_2020.kml")
112 >>> kml.write(outfile, prettyprint=True, precision=3) # doctest: +ELLIPSIS
113
114
115 The resulting KML file can be opened in Google Earth or any other KML viewer.
116
117
118 Build an animated over time KML visualization
119 ----------------------------------------------
120
121 This example shows how to build an animated KML visualization over time.
122 We will use the same data as in the previous example, but this time we will
123 create a KML file that shows the CO2 emissions accumulating from 1995 to 2022.
124
125 .. image:: co2growth.gif
126 :alt: CO2 emissions per capita growth
127 :align: center
128 :width: 800px
129 :target: https://ion.cesium.com/stories/viewer/?id=602c8c64-72aa-4c57-8a01-752b6fbc62d0
130
131 (click on the image to see the full visualization in Cesium Ion)
132
133 First we import the necessary modules:
134
135 .. code-block:: pycon
136
137 >>> import csv
138 >>> import pathlib
139 >>> import random
140 >>> import datetime
141 >>> import shapefile
142 >>> from pygeoif.factories import force_3d
143 >>> from pygeoif.factories import shape
144 >>> import fastkml
145 >>> import fastkml.containers
146 >>> import fastkml.features
147 >>> import fastkml.styles
148 >>> import fastkml.times
149 >>> from fastkml.enums import AltitudeMode, DateTimeResolution
150 >>> from fastkml.geometry import create_kml_geometry
151
152 Read the shapefile, the CSV file and store the CO2 data for each year:
153
154 .. code-block:: pycon
155
156 >>> co2_csv = pathlib.Path("examples/owid-co2-data.csv")
157 >>> co2_pa = {str(i): {} for i in range(1995, 2023)}
158 >>> with co2_csv.open() as csvfile:
159 ... reader = csv.DictReader(csvfile)
160 ... for row in reader:
161 ... if row["year"] >= "1995":
162 ... co2_pa[row["year"]][row["iso_code"]] = (
163 ... float(row["co2_per_capita"]) if row["co2_per_capita"] else 0
164 ... )
165 ...
166
167
168
169 This time we will create a folder for each country, and a placemark for each year,
170 with the CO2 emissions per capita as the height of the geometry.
171 We will also create a style for each country, which we store at the document level to
172 prevent creating duplicate styles.
173 Each placemark will have a time-span that covers the whole year:
174
175 .. code-block:: pycon
176
177 >>> styles = []
178 >>> folders = []
179 >>> for feature in shp.__geo_interface__["features"]:
180 ... iso3_code = feature["properties"]["ADM0_A3"]
181 ... geometry = shape(feature["geometry"])
182 ... color = random.randint(0, 0xFFFFFF)
183 ... styles.append(
184 ... fastkml.styles.Style(
185 ... id=iso3_code,
186 ... styles=[
187 ... fastkml.styles.LineStyle(color=f"33{color:06X}", width=2),
188 ... fastkml.styles.PolyStyle(
189 ... color=f"88{color:06X}",
190 ... fill=True,
191 ... outline=True,
192 ... ),
193 ... ],
194 ... ),
195 ... )
196 ... style_url = fastkml.styles.StyleUrl(url=f"#{iso3_code}")
197 ... folder = fastkml.containers.Folder(name=feature["properties"]["NAME"])
198 ... co2_growth = 0
199 ... for year in range(1995, 2023):
200 ... co2_year = co2_pa[str(year)].get(iso3_code, 0)
201 ... co2_growth += co2_year
202 ... kml_geometry = create_kml_geometry(
203 ... force_3d(geometry, co2_growth * 5_000),
204 ... extrude=True,
205 ... altitude_mode=AltitudeMode.relative_to_ground,
206 ... )
207 ... timespan = fastkml.times.TimeSpan(
208 ... begin=fastkml.times.KmlDateTime(
209 ... datetime.date(year, 1, 1), resolution=DateTimeResolution.year_month
210 ... ),
211 ... end=fastkml.times.KmlDateTime(
212 ... datetime.date(year, 12, 31), resolution=DateTimeResolution.year_month
213 ... ),
214 ... )
215 ... placemark = fastkml.features.Placemark(
216 ... name=f"{feature['properties']['NAME']} - {year}",
217 ... description=feature["properties"]["FORMAL_EN"],
218 ... kml_geometry=kml_geometry,
219 ... style_url=style_url,
220 ... times=timespan,
221 ... )
222 ... folder.features.append(placemark)
223 ... folders.append(folder)
224 ...
225
226 Finally, we create the KML object and write it to a file:
227
228 .. code-block:: pycon
229
230 >>> document = fastkml.containers.Document(features=folders, styles=styles)
231 >>> kml = fastkml.KML(features=[document])
232 >>> outfile = pathlib.Path("co2_growth_1995_2022.kml")
233 >>> kml.write(outfile, prettyprint=True, precision=3)
234
235
236 You can open the resulting KML file in Google Earth Desktop and use the time slider to
237 see the CO2 emissions per capita grow over time, Google Earth Web does not support
238 time animations, but
239 `Cesium Ion <https://ion.cesium.com/stories/viewer/?id=602c8c64-72aa-4c57-8a01-752b6fbc62d0>`_
240 can display the time animation.