繁体   English   中英

循环多边形时,Python匀称无法找到多边形内的点

[英]Python Shapely Cant Find Points Within Polygon When Looping Polygons

我有一个带有lat和lon的商店位置的csv文件 我也有一个带有美国人口普查区域多边形特征的geojson文件。 我想使用Python查看每个位置存在于哪些多边形中。

我正在使用Shapely Python库的contains()来遍历商店位置的csv文件,获取纬度和经度坐标,然后检查坐标是否存在于geojson文件的多边形之一内。

如果我先遍历每个位置/坐标,然后遍历每个多边形,则使用contains()或inside()来检查多边形是否包含该点,那么我编写的代码就可以成功工作。

但这太慢了,所以我想反过来进行这个过程,并首先遍历polygons / geojson文件,然后对照成千上万的坐标检查成千上万的多边形,而不是反过来。

但是,当我简单地切换循环以对照坐标检查多边形时,contains()不会找到任何匹配项,即使在我首先遍历坐标并针对多边形检查它们时找到了正确的匹配项。 除了反转之外,它是相同的代码。

代码(包含错误):

with open(mapFile) as f:
    data = json.load(f)

    #Loop through features in Geojson file
    for feature in data['features']:

        polygon = shape(feature["geometry"])

        for row in locationsFile:
            #get point coordinates from file
            pointLat = float(row[13])
            pointLon = float(row[14])

            point = Point(pointLon, pointLat)

            print(polygon.contains(point))   
            if polygon.contains(point):

                #Grab data
                newx = feature["properties"]["x"]
                newy = feature["properties"]["y"]
                newz = feature["properties"]["z"]
                #append data
                row.append(newx)
                row.append(newy)
                row.append(newz)
                #update file
                newFile.writerow(row)
                break

此代码可产生准确的结果:

with open(mapFile) as f:
    data = json.load(f)

    #Loop through coordinates in CSV file
    for row in locationsFile:
        #get point coordinates from file
        pointLat = float(row[13])
        pointLon = float(row[14])

        point = Point(pointLon, pointLat)

        #Loop through features in Geojson file
        for feature in data['features']:

            polygon = shape(feature["geometry"])

            if polygon.contains(point):

                #Grab data
                newx = feature["properties"]["x"]
                newy = feature["properties"]["y"]
                newz = feature["properties"]["z"]
                #append data
                row.append(newx)
                row.append(newy)
                row.append(newz)
                #update file
                newFile.writerow(row)
                break

两种情况下, break行为都会有所不同。 它只会打破最里面的循环,在“正确”的情况下,是通过data['features']的循环,但在错误的情况下,是通过locationsFile的循环

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM