Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #draw_map.py: draw a rectilinear world map and save it to output.png
- #Consult https://tools.ietf.org/html/rfc7946 for a specification of several of the types used here
- import shapefile #https://pypi.org/project/pyshp/
- from PIL import Image, ImageDraw
- #downloaded/unzipped from https://www.naturalearthdata.com/downloads/110m-cultural-vectors/, "Admin 0 - Countries" -> "Download Countries"
- SHAPEFILE_PATH = "res/ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp"
- def to_screen_coords(p):
- """convert from lat/long to pixel coordinates using a sensible projection."""
- #1:1 rectilinear projection sure is easy
- return (p[0] + 180, -p[1] + 90)
- def render_poly(seq):
- """render an RFC7946 Polygon instance."""
- #polygons can have multiple independent boundaries (for example, if it's a donut shape), so for wireframe renderings you can think of it more like a collection of polygons
- for linear_ring in seq:
- for idx, p1 in enumerate(linear_ring[:-1]):
- p2 = linear_ring[idx+1]
- coords = (to_screen_coords(p1), to_screen_coords(p2))
- draw.line(coords, fill="black")
- image = Image.new("RGB", (260, 180), "white")
- draw = ImageDraw.Draw(image)
- with shapefile.Reader(SHAPEFILE_PATH) as sf:
- for shape_rec in sf:
- #convert to RFC7946 GeoJSON format
- shape = shape_rec.__geo_interface__
- coords = shape["geometry"]["coordinates"]
- t = shape["geometry"]["type"]
- #handle all geometry types described at https://tools.ietf.org/html/rfc7946#section-3.1.1
- if t == "Point":
- raise NotImplemented #todo
- elif t == "MultiPoint":
- raise NotImplemented #todo
- elif t == "Polygon":
- render_poly(coords)
- elif t == "MultiPolygon":
- for poly in coords:
- render_poly(poly)
- elif t == "MultiLineString":
- raise Exception("I don't know what a MultiLineString even is, to be honest")
- else:
- raise Exception(f"Unknown geometry type {t}")
- image.save("output.png")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement