def extentGeometry(geometries):
    'create extent geometry filters'
    extent_geometries = []
    for geometry in geometries:
            extent = geometry.extent
            array = arcpy.Array()
            extent_vertices = [arcpy.Point(extent.XMin, extent.YMin),arcpy.Point(extent.XMin, extent.YMax),
                               arcpy.Point(extent.XMax, extent.YMax),arcpy.Point(extent.XMax, extent.YMin)]
            array.extend(extent_vertices)
            extent_geometry = arcpy.Polygon(array,geometry.spatialReference)
            extent_filter = arcrest.filters.GeometryFilter(extent_geometry)
            extent_geometries.append(extent_filter)
    return extent_geometries
Пример #2
0
 def asShape(self):
     """returns JSON as arcpy.Geometry() object"""
     if self.geometryType != ESRI_ENVELOPE:
         return arcpy.AsShape(self.json, True)
     else:
         ar = arcpy.Array([
             arcpy.Point(self.json[XMIN], self.json[YMAX]),
             arcpy.Point(self.json[XMAX], self.json[YMAX]),
             arcpy.Point(self.json[XMAX], self.json[YMIN]),
             arcpy.Point(self.json[XMIN], self.json[YMIN])
         ])
         return arcpy.Polygon(ar,
                              arcpy.SpatialReference(self.spatialReference))
Пример #3
0
 def getCurrentBBinWGS84(self):
     cmapdoc = arcpy.mapping.MapDocument("CURRENT")
     cdf = arcpy.mapping.ListDataFrames(cmapdoc, "Layers")[0]
     extentPolygon = arcpy.Polygon(
         arcpy.Array([
             cdf.extent.lowerLeft, cdf.extent.lowerRight,
             cdf.extent.upperRight, cdf.extent.upperLeft
         ]), cdf.spatialReference)
     self.rs = cdf.spatialReference
     extentPolygoninWGS84 = extentPolygon.projectAs(
         "WGS 1984")  #arcpy.SpatialReference(4326)
     ex = extentPolygoninWGS84.extent
     return [ex.YMin, ex.XMin, ex.YMax, ex.XMax]
     del cmapdoc
Пример #4
0
def getHoles(input_fc):
    # Getting the holes
    with arcpy.da.UpdateCursor(input_fc, "SHAPE@") as cur:
        for polygon, in cur:
            if polygon is None: continue
            SR = polygon.spatialReference
            polygon = arcpy.Polygon(
                arcpy.Array(
                    (pt for pt in takewhile(bool, part))
                    for part
                    in polygon.getPart() or arcpy.Array(arcpy.Array())
                ), SR
            )
            cur.updateRow([polygon])
Пример #5
0
def process_nadir(row):
    # Longitude and latitude may be switched in arcmap data OR this script
    coords = (row['longitude'], row['latitude'])
    heading = row['yaw']

    width, height = calculate_width_height(row['flying_height'])
    width = width / 2 * 0.75
    height = height / 2 * 0.75

    poly_array, corners = get_nadir_footprint(calculate_headings(heading),
                                              coords, width, height)

    # Turn poly_array into a polygon and add to the shapefile
    return arcpy.Polygon(poly_array)
Пример #6
0
def create_polygon(coord_l):
    point = arcpy.Point()
    array = arcpy.Array()
    featureList = []
    for feature in coord_l:
        point.x = coord[0]
        point.y = coord[1]
        array.add(point)

    array.add(array.getaObject(0))
    polygon = arcpy.Polygon(array)
    array.removeAll()
    featureList.append(polygon)
    return featureList
Пример #7
0
def poly_filling_up(in_poly_fc, out_poly_fc):
    """
    メソッド名 : poly_filling_up メソッド
    引数 1     : 入力フィーチャ
    引数 2     : 出力フィーチャ
    概要       : ポリゴンを穴埋め
    """
    try:
        arcpy.AddMessage(u"処理開始:")
        in_fc_name = os.path.basename(in_poly_fc)
        in_ws = os.path.dirname(in_poly_fc)
        out_fc_name = os.path.basename(out_poly_fc)
        out_ws = os.path.dirname(out_poly_fc)

        # 出力データの作成
        arcpy.CopyFeatures_management(in_poly_fc, out_poly_fc)

        outcur = arcpy.da.UpdateCursor(out_poly_fc, "SHAPE@")

        for inrow in outcur:
            polygon = arcpy.Array()
            for part in inrow[0]:
                new_part = arcpy.Array()
                # Nullになるポイント(interior ring の最初)を取得
                null_point = 0
                for i in range(len(part)):
                    if part[i] == None:
                        null_point = i
                        break
                # 穴あきポリゴンでない場合パートの数そのまま
                if null_point == 0:
                    polygon.add(part)
                # 穴あきポリゴンの場合パートの数をinterior ringの一つ前のポイントまでに
                else:
                    for j in range(null_point):
                        new_part.add(part[j])
                    polygon.add(new_part)
            if len(polygon) > 0:
                new_poly = arcpy.Polygon(polygon)
                inrow[0] = new_poly
                outcur.updateRow(inrow)

        # 後始末
        del outcur

        arcpy.AddMessage(u"処理終了:")
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))
    except Exception as e:
        arcpy.AddError(e.args[0])
Пример #8
0
def selectSqueeSARData(extent, layer):
    """
    This function translates the extent selected by the user into the spatial
    reference of the SqueeSAR layer and identifies the features within the
    selected area.

    Args:
        extent (Extent): the extent object identifying the user-selected area.

        layer (Layer): a reference to the layer containing the SqueeSAR data.

    Returns:
        nfeat (int): the number of features (scatterers) within the selected area.

        spatref (SpatialReference): the spatial reference of the SqueeSAR layer.

    Raises:
        UserWarning: if there is no data within the selection.

    """
    # Get the spatial reference of the SqueeSAR layer
    spatref = ap.Describe(layer).spatialReference

    # Convert the rectangle extent to a polygon
    area = ap.Array()  # Create empty array
    area.add(extent.lowerLeft)
    area.add(extent.lowerRight)
    area.add(extent.upperRight)
    area.add(extent.upperLeft)
    area.add(extent.lowerLeft)
    poly = ap.Polygon(area, spatref)

    # Select the data
    ap.SelectLayerByLocation_management(layer, "WITHIN", poly, 0.0, "NEW_SELECTION")

    # Evaluate the number of selected features
    nfeat = ap.GetCount_management(layer).getOutput(0)

    if nfeat == "0":
        pa.MessageBox("No features were available within the selection boundaries",
                      "Warning",
                      0)

        raise UserWarning("No features!")

    print("{0} feature(s) selected within:\n".format(nfeat) +
          "Lat: {0} to {1}\n".format(extent.YMin, extent.YMax) +
          "Lon: {0} to {1}\n".format(extent.XMin, extent.XMax))

    return (int(float(nfeat)), spatref)
Пример #9
0
def _read_multipolygon(geojson_coords, sr):
    #AFAIK ArcGIS doesn't actually support the creation of multipart polygons
    #from the command line. So instead, return a set of polygons to be
    #processed individually.
    #Therefore we will return a set of geometries, and
    logger.debug("Reading multipolygon")
    geom_list = []
    for poly in geojson_coords:
        poly_obj = arcpy.Array()
        for coords in poly:
            poly_obj.add(_get_array(coords))
        geom_list.append(arcpy.Polygon(poly_obj, sr))
    geom = _dissolve_multipart(geom_list)
    return geom, "polygon"
Пример #10
0
def create_sector2(x, y, radius, angle, SectorName):
    print "x,y,radius,angle,SectorName:" + str(x) + "," + str(y) + "," + str(
        radius) + "," + str(angle) + "," + str(SectorName)
    angle_sjx = 90  #默认的扇形的角度
    n = int(20)
    #默认扇形上选取20个点
    angle_x = x + radius  #x旋转的开始位置
    angle_y = y  #y旋转的开始位置
    #创建扇形上的点数组
    array_k = arcpy.Array()
    pnt = arcpy.Point()
    pnt.X = x
    pnt.Y = y
    array_k.add(pnt)
    angle1 = (angle - angle_sjx / 2) * math.pi / 180.0000
    angle2 = (angle + angle_sjx / 2) * math.pi / 180.0000
    #根据角度来计算扇形上的起始点坐标
    x1 = (angle_x - x) * math.cos(angle1) + (angle_y -
                                             y) * math.sin(angle1) + x
    y1 = -(angle_x - x) * math.sin(angle1) + (angle_y -
                                              y) * math.cos(angle1) + y
    x2 = (angle_x - x) * math.cos(angle2) + (angle_y -
                                             y) * math.sin(angle2) + x
    y2 = -(angle_x - x) * math.sin(angle2) + (angle_y -
                                              y) * math.cos(angle2) + y
    pnt1 = arcpy.Point(x1, y1)
    pnt2 = arcpy.Point(x2, y2)
    #扇形上的起始点为所有点的第二个点
    array_k.add(pnt1)
    for k in range(n):  #计算angle_sjx个点的坐标
        anglek = (angle - angle_sjx / 2 + k * angle_sjx / n) * math.pi / 180.0
        xk = (angle_x - x) * math.cos(anglek) + (angle_y -
                                                 y) * math.sin(anglek) + x
        yk = -(angle_x - x) * math.sin(anglek) + (angle_y -
                                                  y) * math.cos(anglek) + y
        pntk = arcpy.Point(xk, yk)
        array_k.add(pntk)
    #print "pntk:x"+str(k)+":"+str(xk)+",y"+str(k)+":"+str(yk)
    array_k.add(pnt2)
    array_k.add(array_k.getObject(0))  #这里又加了一次起始点
    print "array_k的长度为:" + str(len(array_k))
    poly = arcpy.Polygon(array_k)
    array_k.removeAll()  #清空array_k
    #生成扇形图层
    outputSectorFeatureF = os.path.join(
        os.path.split(outputSectorFeature)[0], SectorName)
    arcpy.CopyFeatures_management(poly, outputSectorFeatureF)
    arcpy.DefineProjection_management(outputSectorFeatureF,
                                      arcpy.SpatialReference(2436))
    arcpy.SetParameterAsText(5, outputSectorFeatureF)
Пример #11
0
    def get_squares(self, line, length):
        squares = list()
        angle = get_angle(line)
        arcpy.AddMessage(angle)
        x = line.firstPoint.X
        y = line.firstPoint.Y
        arcpy.AddMessage(line.firstPoint.X)
        arcpy.AddMessage(line.lastPoint.X)
        arcpy.AddMessage("  ")
        if angle < 45 and angle > -45:
            a = arcpy.Point(x - (length / 2), y + length)
            b = arcpy.Point(x + (length / 2), y + length)
            c = arcpy.Point(x + (length / 2), y)
            d = arcpy.Point(x - (length / 2), y)

            p = arcpy.Point(x - (length / 2), y)
            q = arcpy.Point(x + (length / 2), y)
            r = arcpy.Point(x + (length / 2), y - length)
            s = arcpy.Point(x - (length / 2), y - length)

            squares.append(arcpy.Polygon(arcpy.Array([a, b, c, d])))
            squares.append(arcpy.Polygon(arcpy.Array([p, q, r, s])))
        else:
            a = arcpy.Point(x - length, y + (length / 2))
            b = arcpy.Point(x, y + (length / 2))
            c = arcpy.Point(x, y - (length / 2))
            d = arcpy.Point(x - length, y - (length / 2))

            p = arcpy.Point(x + length, y + (length / 2))
            q = arcpy.Point(x, y + (length / 2))
            r = arcpy.Point(x, y - (length / 2))
            s = arcpy.Point(x + length, y - (length / 2))

            squares.append(arcpy.Polygon(arcpy.Array([a, b, c, d])))
            squares.append(arcpy.Polygon(arcpy.Array([p, q, r, s])))

        return squares
Пример #12
0
def changeStartingVertex(fcInputPoints, fcInputPolygons):

    ## Create Geometry Object for Processing input points.
    g = arcpy.Geometry()
    geomPoints = arcpy.CopyFeatures_management(fcInputPoints, g)

    listPointCoords = []
    for point in geomPoints:
        listPointCoords.append([point.centroid.X, point.centroid.Y])
        #arcpy.AddMessage(str(point.centroid.X) + ","+ str(point.centroid.Y))

    with arcpy.da.UpdateCursor(fcInputPolygons,
                               ["OID@", "SHAPE@"]) as ucPolygons:
        for featPolygon in ucPolygons:
            vertexList = []
            #arcpy.AddMessage("Feature: " + str(featPolygon[0]))
            i = 0
            iStart = 0
            for polygonVertex in featPolygon[1].getPart(0):  # shape,firstpart
                if polygonVertex:
                    #arcpy.AddMessage(' Vertex:' + str(i))
                    vertexList.append([polygonVertex.X, polygonVertex.Y])
                    if [polygonVertex.X, polygonVertex.Y] in listPointCoords:
                        #arcpy.AddMessage("  Point-Vertex Match!")
                        iStart = i
                    else:
                        pass
                        #arcpy.AddMessage("  No Match")
                i = i + 1
            if iStart == 0:
                newVertexList = vertexList
                #arcpy.AddMessage("No Change for: " + str(featPolygon[0]))
            else:
                #arcpy.AddMessage("Changing Vertex List for: " + str(featPolygon[0]))
                newVertexList = vertexList[iStart:i] + vertexList[0:iStart]
                for v in newVertexList:
                    arcpy.AddMessage(str(v[0]) + "," + str(v[1]))
                #listVertexPointObjects = []
                newShapeArray = arcpy.Array()
                for newVertex in newVertexList:
                    #arcpy.AddMessage("Changing Vertex: " + str(newVertex[0]) + ',' + str(newVertex[1]))
                    newShapeArray.add(arcpy.Point(newVertex[0], newVertex[1]))
                    #listVertexPointObjects.append(arcpy.Point(newVertex[0],newVertex[1]))
                #newShapeArray = arcpy.Array(listVertexPointObjects)
                newPolygonArray = arcpy.Polygon(newShapeArray)

                ucPolygons.updateRow([featPolygon[0], newPolygonArray])

    return
Пример #13
0
def IsoplethLinesToPolygons(lineFC, polyFC, fieldname="contour"):
    """Builds a featureclass named polyFC, by creating a polygon
    from all the lines in lineFC that have the same value in the
    field named fieldname.  The largest values in fieldname are
    written first, this will provide the expected polygon stacking. 
    
    arcpy.FeatureToPolygon_management creates polygons from lines,
    but it does not copy attributes, doesn't guarantee order, and
    doesn't merge polygons with the same value."""

    uniqueValues = GetUniqueValues(lineFC,fieldname)

    if not uniqueValues:
        utils.warn("No field named '"+fieldname+"' in "+lineFC)
        return

    workspace,featureClass = os.path.split(polyFC)
    arcpy.CreateFeatureclass_management(workspace,featureClass, 
                                        "Polygon", lineFC, "SAME_AS_TEMPLATE",
                                        "SAME_AS_TEMPLATE", lineFC)       
    # I use lineFC as a template for polyFC, even though I don't need all fields
    # (typically there is only the 'contour' field, besides the standard fields)
    # I do this to avoid adding a field (schema lock bug with PGDB)
    # and I don't want to worry about the data type (float or int) of 'contour'
    
    lineDescription = arcpy.Describe(lineFC)
    polyDescription = arcpy.Describe(polyFC)

    uniqueValues = list(uniqueValues)
    uniqueValues.sort()
    uniqueValues.reverse() #builds biggest to smallest
    polys = arcpy.InsertCursor(polyFC)
    for value in uniqueValues:
        query = BuildQuery(lineFC,fieldname,value)
        lines = arcpy.SearchCursor(lineFC,query)
        poly = polys.newRow()
        array = arcpy.Array()
        for line in lines:
            shape = line.getValue(lineDescription.shapeFieldName)
            for i in range(shape.partCount):
                array.add(shape.getPart(i))
        newshape = arcpy.Polygon(array)
        poly.setValue(polyDescription.shapeFieldName, newshape)
        poly.setValue(fieldname, value)
        polys.insertRow(poly)

    #Close/Delete row/cursor objects to remove the exclusive lock
    del poly
    del polys
Пример #14
0
def create_polygon(self):
    point = arcpy.Point()
    array = arcpy.Array()
    featureList = []
    for feature in self:
        for coord in feature:
            point.X = coord[0]
            point.Y = coord[1]
            array.add(point)

        array.add(array.getObject(0))
        polygon = arcpy.Polygon(array)
        array.removeAll()
        featureList.append(polygon)
    return featureList
Пример #15
0
def draw_poly(coord_list, sr, y, x):
    """
	Convert a Python list of coordinates to an ArcPy polygon feature
	Reference from : Curtis Price, USGS, [email protected]
	coord_list(List): list of coordinates, example:
		[
			[
				['J1', '4', '3436538.1950', '34012885.9660'],
				['J2', '4', '3436540.7970', '34012503.6880'],
				['J16', '4', '3436517.6030', '34012500.1670'],
				['J17', '4', '3436520.2950', '34012503.2740']
			]
			[
				['J1', '5', '3465542.0410', '34102863.3320'],
				['J2', '5', '3436538.9340', '34702571.2020'],
				['J3', '5', '3536539.5550', '35762578.0360'],
				['J4', '5', '3536544.1120', '35762582.1780'],
				['J5', '5', '3536550.5320', '35762585.2840'],
				['J6', '5', '3536556.9520', '35762586.9410']
			]
		]
	 sr: 投影系
	  y(Int): y坐标行数
	  x(Int): x坐标行数
	"""
    parts = arcpy.Array()
    yuans = arcpy.Array()
    yuan = arcpy.Array()
    for part in coord_list:
        for pnt in part:
            if pnt:
                yuan.add(arcpy.Point(pnt[y], pnt[x]))
            else:
                # null point - we are at the start of a new ring
                yuans.add(yuan)
                yuan.removeAll()
        # we have our last ring, add it
        yuans.add(yuan)
        yuan.removeAll()
        # if we only have one ring: remove nesting
        if len(yuans) == 1:
            yuans = yuans.getObject(0)
        parts.add(yuans)
        yuans.removeAll()
    # if single-part (only one part) remove nesting
    if len(parts) == 1:
        parts = parts.getObject(0)
    return arcpy.Polygon(parts, sr)
Пример #16
0
def createFeatures(coordList):

    for feature in coordList:
        point = arcpy.Point()
        array = arcpy.Array()

        for coordPair in feature:
            point.X = coordPair[0]
            point.Y = coordPair[1]
            array.add(point)

        array.add(array.getObject(0))

        polygon = arcpy.Polygon(array)

        featureList.append(polygon)
Пример #17
0
	def generatePolygon(self,latLonList):
		try:
			lll = eval(latLonList)
			innerArray = []
			log.debug("Appending points")
			for p in lll:
				innerArray.append(arcpy.Point(float(p["lng"]),float(p["lat"])))
			if len(innerArray) < 3:
				return False
			log.debug("Creating arcPy array")
			array = arcpy.Array(innerArray)
			log.debug("Creating polyline")
			polygon = arcpy.Polygon(array,arcpy.SpatialReference(4326))
			return polygon
		except Exception as e:
			log.exception("Error in generatePolygon()")
Пример #18
0
def makePolygon(pointArray):
    n = 0
    pts = arcpy.Array()
    while n < len(pointArray):
        longitude = pointArray[n]
        latitude = pointArray[n + 1]
        pt = arcpy.Point(X = longitude, Y = latitude)
        pts.add(pt)
        n += 2
    pts.add(pts[0])
    poly = arcpy.Polygon(pts)
    if poly.area == 0:
        polyline = arcpy.Polyline(pts)
        poly = polyline.buffer(0.0015)

    return poly
Пример #19
0
def Farmpoint_polygon(farm_point):
    polygonGeometryList = []
    for farm_point_list in farm_point:

        array = arcpy.Array()
        for dict in farm_point_list:
            point = arcpy.Point()
            point.X = dict['X']
            point.Y = dict['Y']
            array.append(point)
        polygon = arcpy.Polygon(array)
        print(array.count)

        polygonGeometryList.append(polygon)
    print(len(polygonGeometryList))
    arcpy.CopyFeatures_management(polygonGeometryList, r'E:\first_addin_picture\polygon\house\farm.shp')
Пример #20
0
def arcpnts_poly(in_, out_type='Polygon', SR=None):
    """Convert arcpy Point lists to poly* features
    : out_type - either 'Polygon' or 'Polyline'
    :
    """
    s = []
    for i in in_:
        arr = arcpy.Array(i)
        if out_type == 'Polyline':
            g = arcpy.Polyline(arr, SR)
        elif out_type == 'Polygon':
            g = arcpy.Polygon(arr, SR)
        elif out_type == 'Points':
            g = arcpy.arcpy.Multipoint(arr[0], SR)
        s.append(g)
    return s
Пример #21
0
 def onLine(self, line_geometry):
     array = arcpy.Array()
     part = line_geometry.getPart(0)
     for pt in part:
         array.add(pt)
     array.add(line_geometry.firstPoint)
     polygon = arcpy.Polygon(array)
     if arcpy.Exists("in_memory/polygons"):
         arcpy.Delete_management("in_memory/polygons")
     arcpy.RefreshActiveView()
     arcpy.CopyFeatures_management(polygon, "in_memory/polygons")
     mxd = arcpy.mapping.MapDocument("CURRENT")
     aes = [x for x in arcpy.mapping.ListLayers(mxd) if x.name[0:3] == 'AES'][0]
     poligono = [x for x in arcpy.mapping.ListLayers(mxd) if x.name == 'polygons'][0]
     arcpy.SelectLayerByLocation_management(ccpp, "INTERSECT", poligono, "#", "NEW_SELECTION")
     suma = sum([x[0] for x in arcpy.da.SearchCursor(ccpp, ["CANT_EST"])])
Пример #22
0
def from_wkt(wkt, sr):
    """Creates a polygon geometry from a list of well-known text coordinates.

    :param wkt: well-known text
    :param sr: arcpy spatial reference object
    :rtype : arcpy.Polygon
    """
    import arcpy
    coordinates = wkt[wkt.find('(') + 2: wkt.find(')')].split(',')
    array = arcpy.Array()
    for p in coordinates:
        p = p.replace('(', '')
        pt = p.strip().split(' ')
        array.add(arcpy.Point(float(pt[0]), float(pt[1])))
    poly = arcpy.Polygon(array, sr)
    return poly
Пример #23
0
def createGeometry(pntCoords, geometry_type):
    geometry = arcpy.Geometry()
    spatialRef = arcpy.SpatialReference(4326)
    if geometry_type.lower() == 'point':
        geometry = arcpy.Multipoint(
            arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]),
            spatialRef)
    elif geometry_type.lower() == 'polyline':
        geometry = arcpy.Polyline(
            arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]),
            spatialRef)
    elif geometry_type.lower() == 'polygon':
        geometry = arcpy.Polygon(
            arcpy.Array([arcpy.Point(*coords) for coords in pntCoords]),
            spatialRef)
    return geometry
 def NewGeom_d(self):
     l = [45, 135, 225, 315]
     cursor = arcpy.da.SearchCursor(self.feature, ["SHAPE@XY", self.d_attr])
     cursor_new = arcpy.da.InsertCursor(self.fullpathname, ["SHAPE@"])
     for row in cursor:
         p = row[0]
         d = row[1]
         az = float(self.az)
         array = arcpy.Array()
         for i in l:
             x = p[0] + (d * sqrt(2.0)) * cos(((i + (90 - az)) * pi) / 180)
             y = p[1] + (d * sqrt(2.0)) * sin(((i + (90 - az)) * pi) / 180)
             array.add(arcpy.Point(x, y))
         cursor_new.insertRow([arcpy.Polygon(array)])
         array.removeAll()
     return
Пример #25
0
 def polygon_to_line_no_gap(input_line_, output_polygon):
     array = arcpy.da.FeatureClassToNumPyArray(
         input_line_, ["SHAPE@X", "SHAPE@Y"],
         spatial_reference=coord_system,
         explode_to_points=True)
     if array.size == 0:
         arcpy.AddError(
             "Line has no features, check to ensure it is OK")
     else:
         array2 = arcpy.Array()
         for x, y in array:
             pnt = arcpy.Point(x, y)
             array2.add(pnt)
         polygon = arcpy.Polygon(array2)
         arcpy.CopyFeatures_management(polygon, output_polygon)
     return
Пример #26
0
def get_polygon_from_rings(rings):

    array = arcpy.Array()

    for ring in rings:
        sub_array = arcpy.Array()

        for coords in ring:
            x, y = coords
            pnt = arcpy.Point(x, y)
            sub_array.add(pnt)

        array.add(sub_array)

    sr = arcpy.SpatialReference(4326)
    polygon = arcpy.Polygon(array, sr)
    return polygon
Пример #27
0
 def parseFeatures(cls, maskGmlFile):
     tree = cacheElementTree(maskGmlFile)
     wkid = tree.find('./gml:boundedBy/gml:Envelope', cls.ns).attrib["srsName"].split(":")[-1]
     rids = tree.getroot().attrib["{"+cls.ns["gml"]+"}id"].split("_")
     ts = datetime.datetime.strptime(rids[6], '%Y%m%dT%H%M%S')
     tile = rids[8]
     features = []
     maskFeatures = tree.findall('.//eop:MaskFeature', cls.ns)
     for feature in maskFeatures:
         fid = (feature.attrib["{"+cls.ns["gml"]+"}id"])
         ftype = feature.find("eop:maskType", cls.ns).text
         parray = feature.find("eop:extentOf/gml:Polygon/gml:exterior/gml:LinearRing/gml:posList", cls.ns).text
         coords = [int(coor) for coor in parray.split(" ")]
         points = [[coords[2*i], coords[2*i+1]] for i in range(len(coords)//2)]
         shape = arcpy.Polygon(arcpy.Array([arcpy.Point(*pc) for pc in points]), arcpy.SpatialReference(int(wkid)))
         features.append((fid, ftype, tile, ts, shape))
     return features
    def pointinpolytest(self):

        polyarray = [[0, 0], [5, 0], [5, 5], [0, 5]]

        px = 2
        py = 2

        array = arcpy.Array([arcpy.Point(*coords) for coords in polyarray])

        wb_geometry = arcpy.Polygon(array)
        pTestPoint = arcpy.Point(px, py)
        #containflag = wb_geometry.contains(pTestPoint)
        containflag = pTestPoint.within(wb_geometry)
        if (containflag):
            print("Point in side")
        else:
            print("Point Out side")
Пример #29
0
def arcpnts_poly(in_, out_type='Polygon', SR=None):
    """Convert arcpy Point lists to poly* features
    : out_type - either 'Polygon' or 'Polyline'
    :
    """
    s = []
    for i in in_:
        for j in i:
            if out_type == 'Polygon':
                g = arcpy.Polygon(arcpy.Array(j), SR)
            elif out_type == 'Polyline':
                g = arcpy.Polyline(arcpy.Array(j), SR)
            elif out_type == 'Points':
                j = _flat_(j)
                g = arcpy.Multipoint(arcpy.Array(j), SR)  # check
            s.append(g)
    return s
    def MakeFeatureClass(self):
        print "Building shapefile..."
        arc_start = time.time()

        spatial_ref = "NAD 1983"
        # Arcpy housekeeping
        arcpy.env.workspace = "D:/Faaiz/PythonProjects/SSURGO-GIS-Downloader"
        arcpy.env.overwriteOutput = True
        # Create output FC to store final result
        arcpy.CreateFeatureclass_management("/Results", "SoilCells.shp",
                                            "POLYGON", "", "", "", spatial_ref)
        # Add "SOILTYPE" field
        arcpy.AddField_management("/Results/SoilCells.shp", "SOILTYPE", "TEXT")
        # Iterate through Cells in divided area, create array of points from corner coords, make Polygon.
        for cell in self.areaList:
            pointArray = arcpy.Array()
            pointArray.add(arcpy.Point(cell.lon1, cell.lat1))
            pointArray.add(arcpy.Point(cell.lon2, cell.lat1))
            pointArray.add(arcpy.Point(cell.lon2, cell.lat2))
            pointArray.add(arcpy.Point(cell.lon1, cell.lat2))
            cellPolygon = arcpy.Polygon(pointArray, spatial_ref)
            # Add current polygon to final result FC
            arcpy.Append_management(cellPolygon, "/Results/SoilCells.shp",
                                    "NO_TEST")
        print "Done building shapefile."
        arc_time = (time.time() - arc_start) / 60 / 60
        print str(arc_time) + " hours"
        # Create update cursor for SOILTYPE field
        cursor = arcpy.da.UpdateCursor("/Results/SoilCells.shp", ['SOILTYPE'])
        # Create index variables for populating SOILTYPE field
        i = 0
        # Iterate through returned results, and update SOILTYPE to corresponding Cells soilType using index (i)
        print "Populating SOILTYPE field..."
        pop_start = time.time()

        for row in cursor:
            row[0] = self.areaList[i].soilType
            cursor.updateRow(row)
            i += 1
        # Delete cursor, row, and index
        del cursor
        del row
        del i
        print "Done populating"
        pop_time = (time.time() - pop_start) / 60
        print str(pop_time) + " minutes to populate"