【发布时间】:2018-02-11 06:23:32
【问题描述】:
我需要将地图坐标转换为像素(以便在 html 中制作可点击的地图)。
这是一个示例地图(使用 matplotlib 中的 Basemap 包制作)。我在上面放了一些标签,并试图以像素为单位计算标签的中点:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## Step 0: some points to plot
names = [u"Reykjavík", u"Höfn", u"Húsavík"]
lats = [64.133333, 64.25, 66.05]
lons = [-21.933333, -15.216667, -17.316667]
## Step 1: draw a map using matplotlib/Basemap
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
M = Basemap(projection='merc',resolution='c',
llcrnrlat=63,urcrnrlat=67,
llcrnrlon=-24,urcrnrlon=-13)
x, y = M(lons, lats) # transform coordinates according to projection
boxes = []
for xa, ya, name in zip(x, y, names):
box = plt.text(xa, ya, name,
bbox=dict(facecolor='white', alpha=0.5))
boxes.append(box)
M.bluemarble() # a bit fuzzy at this resolution...
plt.savefig('test.png', bbox_inches="tight", pad_inches=0.01)
# Step 2: get the coordinates of the textboxes in pixels and calculate the
# midpoints
F = plt.gcf() # get current figure
R = F.canvas.get_renderer()
midpoints = []
for box in boxes:
bb = box.get_window_extent(renderer=R)
midpoints.append((int((bb.p0[0] + bb.p1[0]) / 2),
int((bb.p0[1] + bb.p1[1]) / 2)))
这些计算的点彼此之间的相对关系大致正确,但与真实点不重合。下面的代码 sn -p 应该在每个标签的中点放一个红点:
# Step 3: use PIL to draw dots on top of the labels
from PIL import Image, ImageDraw
im = Image.open("test.png")
draw = ImageDraw.Draw(im)
for x, y in midpoints:
y = im.size[1] - y # PIL counts rows from top not bottom
draw.ellipse((x-5, y-5, x+5, y+5), fill="#ff0000")
im.save("test.png", "PNG")
- 红点应位于标签中间。
我猜错误出现在我提取文本框坐标的位置(在步骤 #2 中)。非常感谢任何帮助。
备注
- 也许解决方案类似于this answer?
【问题讨论】:
-
您可以改用底图来绘制红点吗?见matplotlib.org/basemap/api/…
标签: python matplotlib geospatial