鉴于此 GeoJSON 文件,我想呈现 ASCII 艺术世界地图。
我的基本方法是将 GeoJSON 加载到Shapely 中,使用pyproj将点转换为墨卡托,然后对我的 ASCII 艺术网格的每个字符的几何图形进行命中测试。
当以本初子午线为中心时,它看起来(编辑:大部分)OK:
但以纽约市 ( lon_0=-74
)为中心,它突然失控了:
我很确定我在这里的预测有问题。(并且将 ASCII 地图坐标转换为纬度/经度可能比转换整个几何更有效,但我不确定如何。)
import functools
import json
import shutil
import sys
import pyproj
import shapely.geometry
import shapely.ops
# Load the map
with open('world-countries.json') as f:
countries = []
for feature in json.load(f)['features']:
# buffer(0) is a trick for fixing polygons with overlapping coordinates
country = shapely.geometry.shape(feature['geometry']).buffer(0)
countries.append(country)
mapgeom = shapely.geometry.MultiPolygon(countries)
# Apply a projection
tform = functools.partial(
pyproj.transform,
pyproj.Proj(proj='longlat'), # input: WGS84
pyproj.Proj(proj='webmerc', lon_0=0), # output: Web Mercator
)
mapgeom = shapely.ops.transform(tform, mapgeom)
# Convert to ASCII art
minx, miny, maxx, maxy = mapgeom.bounds
srcw = maxx - minx
srch = maxy - miny
dstw, dsth = shutil.get_terminal_size((80, 20))
for y in range(dsth):
for x in range(dstw):
pt = shapely.geometry.Point(
(srcw*x/dstw) + minx,
(srch*(dsth-y-1)/dsth) + miny # flip vertically
)
if any(country.contains(pt) for country in mapgeom):
sys.stdout.write('*')
else:
sys.stdout.write(' ')
sys.stdout.write('\n')
手掌心
相关分类