如何判断给定的坐标是否在某个城市?

How to judge whether or not a given coordinate is in a certain city?

我有一些包含经纬度坐标的原始数据,当我使用 osmnx 的 get_nearest_edges 方法时,我想过滤那些不在给定城市(本例中为旧金山)的坐标。有什么方便的方法可以实现这个功能吗?

这是我的部分代码:

roadId = ox.utils.get_nearest_edges(G, df['longitude'], df['latitude'], method='balltree')
df['startId'] = roadId[:,0]
df['endId'] = roadId[:,1]
startId = roadId[:,0]
endId = roadId[:,1]
gdf_nodes, gdf_edges = ox.graph_to_gdfs(G)
startInfo = gdf_nodes.loc[startId]
endInfo = gdf_nodes.loc[endId]
df['startLat'] = startInfo.loc[:, ['y']].values
df['startLon'] = startInfo.loc[:, ['x']].values
df['endLat'] = endInfo.loc[:, ['y']].values
df['endLon'] = endInfo.loc[:, ['x']].values

第一行的G来自于:

G = ox.graph_from_place('San Francisco, California, USA', network_type='drive')

输出文件是这样的:

latitude 37.61549

longitude -122.38821  

startId 65365765

endId 65365766

startLat 37.708957

startLon -122.392803 

endLat 37.708785 

endLon -122.393012

这个例子就是我想表达的意思,因为结果中的道路不在旧金山,如何在代码中识别并去掉?

你问了两个问题。首先,如何判断一对lat-lng坐标是否在城市边界内?二、如何获取一个城市的bounding box?以下是如何使用 OSMnx(以及 OSMnx 构建于其之上的匀称):

import osmnx as ox
from shapely.geometry import Point
gdf = ox.gdf_from_place('Piedmont, CA, USA')
geom = gdf.loc[0, 'geometry']

# get the bounding box of the city
geom.bounds

# determine if a point is within the city boundary
coords = (-122.24, 37.82)
geom.intersects(Point(coords))