生成一个包含在多边形内的纬度-经度坐标网格。

4
我想在地图上绘制数据。 我希望为特定城市的地图上的特定点(例如到一个或多个预先指定位置的交通时间)生成数据。
我在这里找到了纽约市的数据:https://data.cityofnewyork.us/City-Government/Borough-Boundaries/tqmj-j8zm,看起来他们提供了一个形状文件(shapefile)。 我在想是否有一种方式可以对每个行政区域进行经纬度网格采样(也许可以使用Shapely包等)。
非常抱歉如果我的问题很幼稚,我不太熟悉如何处理这些文件 - 我正在通过这个有趣的项目学习它们。

1个回答

12

我已经想出如何做到这一点。基本上,我只是创建了一个完整的点网格,然后删除那些不在对应于区域的形状文件中的点。以下是代码:

import geopandas
from geopandas import GeoDataFrame, GeoSeries
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import matplotlib.cm as cm
%matplotlib inline
import seaborn as sns
from shapely.geometry import Point, Polygon
import numpy as np
import googlemaps
from datetime import datetime
plt.rcParams["figure.figsize"] = [8,6]

# Get the shape-file for NYC
boros = GeoDataFrame.from_file('./Borough Boundaries/geo_export_b641af01-6163-4293-8b3b-e17ca659ed08.shp')
boros = boros.set_index('boro_code')
boros = boros.sort_index()

# Plot and color by borough
boros.plot(column = 'boro_name')

# Get rid of are that you aren't interested in (too far away)
plt.gca().set_xlim([-74.05, -73.85])
plt.gca().set_ylim([40.65, 40.9])

# make a grid of latitude-longitude values
xmin, xmax, ymin, ymax = -74.05, -73.85, 40.65, 40.9
xx, yy = np.meshgrid(np.linspace(xmin,xmax,100), np.linspace(ymin,ymax,100))
xc = xx.flatten()
yc = yy.flatten()

# Now convert these points to geo-data
pts = GeoSeries([Point(x, y) for x, y in zip(xc, yc)])
in_map =  np.array([pts.within(geom) for geom in boros.geometry]).sum(axis=0)
pts = GeoSeries([val for pos,val in enumerate(pts) if in_map[pos]])

# Plot to make sure it makes sense:
pts.plot(markersize=1)

# Now get the lat-long coordinates in a dataframe
coords = []
for n, point in enumerate(pts):
    coords += [','.join(__ for __ in _.strip().split(' ')[::-1]) for _ in str(point).split('(')[1].split(')')[0].split(',')]

以下是所得到的图表: boroughs borough_gridpoints 我还得到了一个纬度-经度坐标矩阵,用于制作从城市中的每个点到哥伦比亚医学院的交通时间地图。下面是该地图: transit_time_full 以下是地图的局部放大版本,可以看到地图是由单个点组成的: transit_time_zoom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接