给定纬度/经度表示坐标是否在美国大陆范围内

时间:2017-02-28 06:05:04

标签: python shapefile esri matplotlib-basemap pyshp

我想检查特定的纬度/经度是否在美国大陆范围内。我不想使用在线API而且我正在使用Python。

我下载了this shapefile

from shapely.geometry import MultiPoint, Point, Polygon
import shapefile    
sf = shapefile.Reader("cb_2015_us_nation_20m")
shapes = sf.shapes()
fields = sf.fields
records = sf.records()
points = shapes[0].points
poly = Polygon(points)
lon = -112
lat = 48
point = Point(-112, 48)
poly.contains(point)
#should return True because it is in continental US but returns False

样本lon,lat在US边界内,但poly.contains返回False。 我不确定问题是什么以及如何解决问题,以便我可以测试一个点是否在美国大陆。

2 个答案:

答案 0 :(得分:1)

我最终检查了是否lat / lon是在每个州,而不是在美国大陆检查,如果一个点在其中一个州,那么它在美国大陆..

from shapely.geometry import MultiPoint, Point, Polygon
import shapefile
#return a polygon for each state in a dictionary
def get_us_border_polygon():

    sf = shapefile.Reader("./data/states/cb_2015_us_state_20m")
    shapes = sf.shapes()
    #shapes[i].points
    fields = sf.fields
    records = sf.records()
    state_polygons = {}
    for i, record in enumerate(records):
        state = record[5]
        points = shapes[i].points
        poly = Polygon(points)
        state_polygons[state] = poly

    return state_polygons

#us border
state_polygons = get_us_border_polygon()   
#check if in one of the states then True, else False
def in_us(lat, lon):
    p = Point(lon, lat)
    for state, poly in state_polygons.iteritems():
        if poly.contains(p):
            return state
    return None

答案 1 :(得分:0)

我运行了您的代码并绘制了多边形。它看起来像这样:

bad image of the US

如果您使用此代码运行它:

import geopandas as gpd
import matplotlib.pyplot as plt

shapefile = gpd.read_file("path/to/shapes.shp")
shapefile.plot()
plt.show()
# credit to https://stackoverflow.com/a/59688817/1917407

你会看到这个:

enter image description here

所以,1,你没有在看 CONUS,2,你的情节很无聊。不过,您的代码可以工作,并且会随着 geopandas 图返回 True。