def geometry(self): """returns the feature geometry""" if self._geom is None: if self._dict.has_key('feature'): self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True) elif self._dict.has_key('geometry'): self._geom = arcpy.AsShape(self._dict['geometry'], esri_json=True) return self._geom
def geometry(self): """returns the feature geometry""" if arcpyFound: if self._geom is None: if 'feature' in self._dict: self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True) elif 'geometry' in self._dict: self._geom = arcpy.AsShape(self._dict['geometry'], esri_json=True) return self._geom return None
def geometry(self): """returns the feature geometry""" if not self._wkid is None: sr = arcpy.SpatialReference(self._wkid) else: sr = None if self._geom is None: if self._dict.has_key('feature'): self._geom = arcpy.AsShape(self._dict['feature']['geometry'], esri_json=True) elif self._dict.has_key('geometry'): self._geom = arcpy.AsShape(self._dict['geometry'], esri_json=True) return self._geom
def envelope(self): """return an envelope from shape""" if self.geometryType != ESRI_ENVELOPE: e = arcpy.AsShape(self.json, True).extent return ','.join(map(str, [e.XMin, e.YMin, e.XMax, e.YMax])) else: return ','.join(map(str, [self.json[XMIN], self.json[YMIN], self.json[XMAX], self.json[YMAX]]))
def responseToTable(self, table): ''' :param table: Feature o tabla que se esta evaluando :return: Crea un tabla temporal en el SCRATCH gdb ''' array = [ x.get('attributes') for x in self.jsonresponse.get('features') ] self.identifiers = [[x.get('globalid'), x.get('objectid')] for x in array] self.identifiers.sort(key=lambda x: x[1]) pth = os.path.join(self.scratch, 'temp') feature = arcpy.AsShape(self.jsonresponse, True) if table.split("_")[0] == "GPT": self.copy = arcpy.CopyFeatures_management(feature, pth) arcpy.management.AddField(self.copy, "EVENTID", "GUID") n = 0 with arcpy.da.UpdateCursor(self.copy, ["EVENTID"]) as cursorU: for row in cursorU: mmm = self.identifiers[n][0].upper() row[0] = u'{}'.format('{' + mmm + '}') cursorU.updateRow(row) n = n + 1 del cursorU self.listaCDMTRA = [[x[0], x[1]] for x in arcpy.da.SearchCursor( self.copy, ["EVENTID", self.CDMTRA])] arcpy.DeleteField_management(self.copy, "globalid") if table.split("_")[0] == "TB": self.copy = arcpy.TableToTable_conversion( feature, self.scratch, '{}a{:.5}'.format(table, str(uuid.uuid4())))
def _buildAHPourpoint(self, ppt, wkid): try: arcpy.env.workspace = self.__TempLocation__ arcpy.env.overwriteOutput = False #get spatial ref wkid = int(wkid) sr = arcpy.SpatialReference(wkid) pourPoint = {"type": "Point", "coordinates": json.loads(ppt)} arcpy.env.overwriteOutput = True FC = arcpy.CreateFeatureclass_management("in_memory", "FC", "POINT", spatial_reference=sr) #add required attributes t_fields = (("Name", "TEXT"), ("Descript", "TEXT"), ("SnapOn", "SHORT"), ("SrcType", "SHORT"), ("BATCHDONE", "SHORT")) for t_field in t_fields: arcpy.AddField_management(FC, *t_field) # Create insert cursor for table fields = [i[0] for i in t_fields] fields.insert(0, 'SHAPE@') with arcpy.da.InsertCursor(FC, fields) as cursor: cursor.insertRow( [arcpy.AsShape(pourPoint), "ags101", "", None, None, None]) #next cursor return FC except: tb = traceback.format_exc() print tb
def loadJson(self, geom, array): feature = {'gpl': self.JSON.gpl, 'gpt': self.JSON.gpt} jsonOpen = open(feature[geom], "r") jsonLoad = json.load(jsonOpen) jsonOpen.close() jsonLoad["features"] = array json2shp = arcpy.AsShape(jsonLoad, True) return json2shp
def geometry(self): """returns arcpy geometry object Warning: output is unprojected use the projectAs(wkid, {transformation_name}) method to project geometry """ if self.esri_json: return arcpy.AsShape(self.esri_json, True) return None
def loadData(self): jsonOpen = open(self.gptJSON, "r") jsonLoad = json.load(jsonOpen) jsonOpen.close() jsonLoad["features"] = self.container json2shp = arcpy.AsShape(jsonLoad, True) self.delRows(self.gpt.path) self.delRows(self.glb.path) arcpy.Append_management(json2shp, self.gpt.path, "NO_TEST") self.add_codhoja_annotation()
def commit(): starttime = datetime.datetime.now() spatialReference={'wkt':'PROJCS["SH",GEOGCS["GCS_Beijing_1954",DATUM["D_Beijing_1954",SPHEROID["Krasovsky_1940",6378245.0,298.3]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",8.0],PARAMETER["False_Northing",-3457143.04],PARAMETER["Central_Meridian",121.4671519444444],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]'} cutpolygon={"rings": [[[-21182.21789336484, 3622.4762820750475], [-19846.069387733936, 3344.6632264479995], [-18602.525233979337, 2603.828411443159], [-15573.040008341894, 1519.0345751922578], [-14699.913262089714, 341.63638705946505], [-15242.310180216096, -1232.637594819069], [-17332.522693973966, -650.5530973169953], [-18060.128315851092, 606.2202495634556], [-19660.860683985054, 1479.3469958156347], [-21248.363858991303, 2352.473742067814], [-21182.21789336484, 3622.4762820750475]]], "spatialReference": {"wkt": "PROJCS[\"ShangHaiCity\",GEOGCS[\"GCS_Beijing_1954\",DATUM[\"D_Beijing_1954\",SPHEROID[\"Krasovsky_1940\",6378245.0,298.3]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",8.0],PARAMETER[\"False_Northing\",-3457143.04],PARAMETER[\"Central_Meridian\",121.4671519444444],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"}} result=cutpolygon_t = arcpy.AsShape(cutpolygon,True) arcpy.SetParameterAsText(2, cutpolygon_t.JSON) print result print cutpolygon_t.JSON print u"执行时间共 "+str((datetime.datetime.now()-starttime).seconds)+u"秒"
def create_recordset(fc): """ create Record Set from Feature Class """ arcpy.AddMessage("Creating record set...") fs = arcpy.FeatureSet(fc) # create dict so convert_fs_to_rs function will work dic = json.loads(fs.JSON) recset_text = json.dumps(convert_fs_to_rs(dic)) # convert string to RecordSet object recset = arcpy.AsShape(recset_text, True) return recset
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))
def loadData( self,geom, array,): # feature = {"pnt": self.jsonfiles.gpt, "lin": self.jsonfiles.gpl, "pol": self.jsonfiles.gpo} feature = {"pol": self.rutajsonpol} jsonOpen = open(feature[geom], "r") jsonLoad = json.load(jsonOpen) jsonOpen.close() jsonLoad["features"] = array print jsonLoad json2shp = arcpy.AsShape(jsonLoad, True) self.delRows(geom) arcpy.Append_management(json2shp, self.outFc[geom], "NO_TEST")
def test_CSV(self, keep=True): rWriter = testGP.ReportWriter("CSV") inputJSON = Generator.generateInputString_CSV() featureSet = arcpy.AsShape(json.loads(inputJSON)['featureSet'], True) testObject = testGP.FieldObject(featureSet) testObject.setFormats({"date": "dd-MM-yyyy", 'floatPrecision': 1}) fPath = "" try: fPath = rWriter.write(testObject, doZip=False) except Exception, e: print "Failed writing CSV: " + e.message return 0
def getFeatures(self, url, objectIds, fields, outFeatureClass=''): try: if ('' == outFeatureClass): outFeatureClass = arcpy.CreateScratchName( "Feat_", "", "FeatureClass", arcpy.env.scratchWorkspace) # Construct the URL and data for query request queryURL = url + "/query" queryContent = self._constructQuery(objectIds, fields, getGeometry=True) print queryContent # Query the server req = urllib2.Request(queryURL, queryContent) response_stream = urllib2.urlopen(req) response = response_stream.read() print response # Parse the response into features esriJSON = json.loads(response) ## Get the non-geometry attributes from the response #recordSet = arcpy.AsShape(esriJSON, True) #recordTable = arcpy.CreateScratchName("Feat_", "", "FeatureClass", arcpy.env.scratchWorkspace) #recordSet.save() # Add in the geometry information assert "esriGeometryPolygon" == esriJSON['geometryType'], str( "Only polygons are supported. Requested: " + str(esriJSON['geometryType'])) tempFeatureClassName = arcpy.CreateScratchName( "tmp_", "", "FeatureClass") print tempFeatureClassName FeatureClass = (arcpy.CreateFeatureclass_management( arcpy.env.scratchWorkspace, tempFeatureClassName, "POLYGON")) #arcpy.env.overwriteOutput=True #FeatureClass = (arcpy.CreateFeatureclass_management('C:\JenData\IMV\ScISR Extraction\RasterScISREdges.gdb', 'temp3', "POLYGON")) featureList = [] for entry in esriJSON['features']: geom = arcpy.AsShape(entry["geometry"], True) featureList.append(geom) arcpy.CopyFeatures_management(featureList, FeatureClass) raise Exception("Working on this method: getFeatures") return outFeatureClass except Exception, e: raise e
def test_KMZ(self, keep=False): try: rWriter = testGP.ReportWriter("KMZ") testObject = testGP.FeatureObject() inputJSON = Generator.generateInputString_KMZ() featureSet = arcpy.AsShape(json.loads(inputJSON)['featureSet'], True) testObject.setFeatureSet(featureSet) rFile = rWriter.write(testObject) if keep: print rFile else: arcpy.Delete_management(rFile) return 1 except Exception, e: print "Failure: "+e.message return 0
def __init__(self): print "Test - FeatureObject" inputJSON_str = Generator.generateInputString_KMZ() fsJSON = json.loads(inputJSON_str)['featureSet'] featureSet = arcpy.AsShape(fsJSON, True) try: testObject = testGP.FeatureObject() testObject.setFeatureSet(featureSet) newFeatureSet = testObject.getFeatureSet() fs = json.loads(newFeatureSet.JSON) print "Passed" except Exception, e: print "Failed: " + e.message
def load_features(file_gdb_path, fc_name, features): fc = file_gdb_path + '/' + fc_name try: rows = arcpy.InsertCursor(fc) fields = {field.name: field for field in arcpy.ListFields(fc)} for feature in features: row = rows.newRow() row.setValue('SHAPE', arcpy.AsShape(feature['geometry'], True)) for name, value in feature['attributes'].iteritems(): field = fields.get(name) if field and field.editable: row.setValue(name, value) rows.insertRow(row) finally: if row: del row if rows: del rows
def test_SHP(self, keep=False): try: arcpy.env.workspace = "C:\Users\jenn6701\Documents\ArcGIS\Default.gdb" rWriter = testGP.ReportWriter("SHP") testObject = testGP.FeatureObject() inputJSON = Generator.generateInputString_KMZ() featureSet = arcpy.AsShape(json.loads(inputJSON)['featureSet'], True) testObject.setFeatureSet(featureSet) rFile = rWriter.write(testObject) if keep: print rFile else: arcpy.Delete_management(rFile) return 1 except Exception, e: print "Failure: "+e.message return 0
def generate_polyline_objects_from_json(json_response): # Route features features = json_response["routes"]["features"] spatialref = json_response["routes"]["spatialReference"] # Use AsShape to convert Esri JSON to polyline features polylines = [] for feature in features: esri_json = { "paths": feature["geometry"]["paths"], "spatialReference": spatialref } polylines.append(arcpy.AsShape(esri_json, True)) return polylines
def loadData(self, geom, array): feature = { "pnt": self.jsonfiles.gpt, "lin": self.jsonfiles.gpl, "pol": self.jsonfiles.gpo } jsonOpen = open(feature[geom], "r") jsonLoad = json.load(jsonOpen) jsonOpen.close() jsonLoad["features"] = array json2shp = arcpy.AsShape(jsonLoad, True) # if geom == 'lin': # json2shp = arcpy.SplitLine_management(json2shp, 'in_memory\splitline') self.delRows(geom) arcpy.Append_management(json2shp, self.outFc[geom], "NO_TEST") return json2shp
def dictionary_to_feature_class(json_dict, out_fc): """ Converts a dictionary of features from a feature services to a local feature class Inputs: json_dict - dictionary - derived dictionary from feature service out_fc - string - full path of where the feature class will be saved. Output: path of saved feature class as string """ arcpy.env.overwriteOutput = True oid_fld = json_dict['objectIdFieldName'] field_names = [] geomType = json_dict['geometryType'] sr = arcpy.SpatialReference(json_dict['spatialReference']['latestWkid']) arcpy.CreateFeatureclass_management( out_path=os.path.dirname(out_fc), out_name=os.path.basename(out_fc), geometry_type=__lookUpGeometry(geomType), spatial_reference=sr) for field in json_dict['fields']: if field['name'] != json_dict['objectIdFieldName']: field_names.append(field['name']) arcpy.AddField_management(out_fc, field['name'], __lookUpFieldType(field['type'])) field_names.append("SHAPE@") icur = arcpy.da.InsertCursor(out_fc, field_names) for feature in json_dict['features']: template = feature['geometry'] template['spatialReference'] = json_dict['spatialReference'][ 'latestWkid'] geom = arcpy.AsShape(json.dumps(template), True) row = [""] * len(field_names) for k, v in feature['attributes'].iteritems(): if k != oid_fld: row[field_names.index(k)] = v row[field_names.index("SHAPE@")] = geom icur.insertRow(row) del row del geom del template del icur del field_names del oid_fld del sr return out_fc
def sync_to_featureclass(out_workspace, fc_name, fields, wkid, geomType, features, objectIdField): """ converts the sync replication to a local feature class Inputs: out_workspace - string - geodatabase path of the save location fc_name - string - name of feature class fields - list of dictionaries obtained from feature service wkid - spatial reference entry from feature service geomType -string - feature service geometry type features - list - items to add to feature class objectIdField - string - nice of OID field Ouput: location of feature class as string. """ arcpy.env.overwriteOutput = True field_names = ["SHAPE@"] sr = arcpy.SpatialReference(wkid['latestWkid']) out_fc = arcpy.CreateFeatureclass_management( out_path=out_workspace, out_name=fc_name, geometry_type=__lookUpGeometry(geomType), spatial_reference=sr)[0] for field in fields: if field['name'] != objectIdField: field_names.append(field['name']) arcpy.AddField_management(out_fc, field['name'], __lookUpFieldType(field['type'])) icur = arcpy.da.InsertCursor(out_fc, field_names) for feature in features: template = feature['geometry'] template['spatialReference'] = wkid['latestWkid'] geom = arcpy.AsShape(json.dumps(template), True) row = [""] * len(field_names) for k, v in feature['attributes'].iteritems(): if k != objectIdField: row[field_names.index(k)] = v row[field_names.index("SHAPE@")] = geom icur.insertRow(row) del row del geom del template del icur del field_names return out_fc
def requestData(self): data = self.listaOids chunks = [data[x:x + 1000] for x in xrange(0, len(data), 1000)] for n in chunks: print(len(n)) n = ','.join([str(x) for x in n]) response = requests.post(self.url, data={ 'objectIds': n, 'outFields': "*", 'f': 'pjson' }) res = json.loads(response.text) feature = arcpy.AsShape(res, True) if arcpy.Exists(self.pth) == False: arcpy.CopyFeatures_management(feature, self.pth) else: arcpy.Append_management(feature, self.pth, 'NO_TEST')
def get_isochrone(self, point, target_epsg, mode, time_sec, walk_speed): params = self.isochrone_params.copy() params['cutoffSec'] = time_sec params['mode'] = mode params['walkSpeed'] = walk_speed if point.epsg != self.epsg: point.transform(self.epsg) params['fromPlace'] = '{y},{x}'.format(y=point.y, x=point.x) r = requests.get(self.isochrone_url, params=params, verify=False) r.raise_for_status() geojson = r.json() geom_json = geojson['features'][0]['geometry'] coords = geom_json['coordinates'] new_coords = [] p1 = Proj(init='epsg:{}'.format(self.epsg)) p2 = Proj(init='epsg:{}'.format(target_epsg)) for a in coords: new_inner_list = [] for b in a: arr = np.asarray(b) new_arr = transform(p1, p2, arr[:, 0], arr[:, 1]) new_list = np.array(zip(*new_arr)).tolist() new_inner_list.append(new_list) new_coords.append(new_inner_list) geom_json['coordinates'] = new_coords iso_poly = arcpy.AsShape(geom_json) #if iso_poly.partCount == 0: #return None #b = arcpy.DefineProjection_management(iso_poly, arcpy.SpatialReference(4326)) #epsg = self.epsg #parts = [] #for part in iso_poly: #points = [] #for point in part: #p = arcpy.PointGeometry(point, #arcpy.SpatialReference(self.epsg)) #points.append( #p.projectAs(arcpy.SpatialReference(31467)).firstPoint) #parts.append(arcpy.Array(points)) #poly_points = arcpy.Array(parts) #polygon = arcpy.Polygon(poly_points) return iso_poly
def main(): try: _pathTemp = os.path.join(os.getcwd(), 'TEMP') removeFile(_pathTemp) _inFC = os.path.join(arcpy.env.workspace,'Poly.shp') arcpy.MakeFeatureLayer_management(_inFC, 'Poly') for row in arcpy.da.SearchCursor('Poly', ["OID@", "SHAPE@"]): _partnum = 0 for part in row[1]: _tempName = 0 for pnt in part: if pnt: _jsonPointESRI = {"type": "Point", "coordinates": [pnt.X, pnt.Y], "spatialReference": {"wkid": 4326}} _outFC_PNT = arcpy.AsShape(_jsonPointESRI) _bufferFC = arcpy.Buffer_analysis( in_features =_outFC_PNT, out_feature_class =os.path.join(_pathTemp, 'BUFFER_{}.shp'.format(_tempName)), buffer_distance_or_field ='1 Meters', line_side ='FULL', line_end_type ='ROUND', dissolve_option ='ALL' ) _clipFC = arcpy.Clip_analysis('Poly', _bufferFC, os.path.join(_pathTemp, 'CLIP_{}.shp'.format(_tempName))) with arcpy.da.SearchCursor(_clipFC,['SHAPE@AREA']) as cursor: for row in cursor: _angulo = ((row[0]*360)/math.pi) print('Vertex angle (X - {0}, Y - {1}): {2}'.format(pnt.X,pnt.Y,_angulo)) else: print("Interior") _tempName += 1 _partnum += 1 except IOError as err: errorTime = time.strftime("%H:%M:%S") print("Error OS {0}").format(err) with open(os.path.join(os.path.dirname(__file__), 'log.txt'), 'a') as f: f.write(str(errorTime)+ '\n') f.write(err.message + '\n') f.close()
def as_dicts( url: str, *, field_names: Optional[Iterable[str]] = None, service_where_sql: Optional[str] = None, include_geometry: bool = True, spatial_reference_item: SpatialReferenceSourceItem = None, ) -> Iterator[dict]: """Generate mappings of feature attribute name to value. Notes: Use ArcPy cursor token names for object IDs and geometry objects/properties. Args: url: URL for the service endpoint. field_names: Names of fields to include in generated dictionary. Names will be the keys in the dictionary mapping to their attributes values. If set to None, all fields will be included. Do not include geometry field; use `include_geometry` to have added. include_geometry: Add geometry attribute to dictionary under "SHAPE@" key if True. service_where_sql: SQL where-clause for service subselection. spatial_reference_item: Item from which the spatial reference of the output geometry will be derived. If set to None, will use spatial reference of the service. """ # `spatial_reference_item = None` will return instance with wkid being None. wkid = SpatialReference(spatial_reference_item).wkid feature_layer = arcgis.features.FeatureLayer(url) feature_set = feature_layer.query( where=service_where_sql if service_where_sql else "1=1", out_fields="*" if field_names is None else list(field_names), out_sr=wkid, ) for feature in feature_set.features: feature_dict = feature.attributes if include_geometry: if "spatialReference" not in feature.geometry: feature.geometry["spatialReference"] = {"wkid": wkid} feature_dict["SHAPE@"] = arcpy.AsShape(feature.geometry, esri_json=True) yield feature_dict
def build_track_geometry(point_file, prior_last_point, start_time, end_time, keys): """Build and return a polyline, and last point for a track log.""" if prior_last_point: path = [prior_last_point] else: path = [] point = None for line in point_file: items = line.split(",") timestamp = items[keys[T]] if timestamp <= start_time: path = [] if timestamp < start_time: continue point = [float(items[keys[X]]), float(items[keys[Y]])] path.append(point) if timestamp == end_time: break esri_json = {"paths": [path], "spatialReference": {"wkid": 4326}} polyline = arcpy.AsShape(esri_json, True) return polyline, point
def parse_geometry(gj_geom): """ Grabs GeoJSON geometry, returns an Esri geometry object and its description in a dictionary :param gj_geom: GeoJSON ['geometry'] entry :returns: dict """ try: esri_geom = arcpy.AsShape(gj_geom) if gj_geom['type'] == 'Point': return {"type": "POINT", "esri_geom": esri_geom} elif gj_geom['type'] in ['LineString', 'MultiLineString']: return {"type": "POLYLINE", "esri_geom": esri_geom} elif gj_geom['type'] in ['Polygon', 'MultiPolygon']: return {"type": "POLYGON", "esri_geom": esri_geom} else: print("Not a Point, Line or Polygon feature.") return False except KeyError as ke: print(f"Error: {ke}. Malformed JSON. Could not parse.") return False
def asArcPyObject(self): """ returns the Polyline as an ESRI arcpy.Polyline object """ return arcpy.AsShape(self.asDictionary, True)