生成落在多边形内的经纬度坐标网格

Generate grid of latitude-longitude coordinates that fall within polygon

我正在尝试将数据绘制到地图上。我想为特定城市的地图上的特定点生成数据(例如,到一个或多个预先指定位置的运输时间)。

我在这里找到了纽约市的数据:https://data.cityofnewyork.us/City-Government/Borough-Boundaries/tqmj-j8zm

看起来他们有可用的 shapefile。我想知道是否有一种方法可以在每个自治市镇的 shapefile 范围内对经纬度网格进行采样(可能使用 Shapely 包等)。

抱歉,如果这太天真了,我对使用这些文件不是很熟悉——我正在做一个有趣的项目来了解它们

我知道怎么做了。本质上,我只是创建了一个完整的点网格,然后删除了那些不属于与行政区相对应的形状文件的点。这是代码:

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(',')]

结果如下图:

我还得到了一个经纬度坐标矩阵,用于为城市中的每个点制作运输时间地图到哥伦比亚医学院。这是地图:

还有一个放大版本,这样您就可以看到地图是如何由各个点组成的: