def exportResults(geocodeResultObject, out_fc): """exports the geocode results to feature class Required: geocodeResultObject -- results from geocode operation, must be of type GeocodeResult. out_fc -- full path to output shapefile """ if isinstance(geocodeResultObject, GeocodeResult): handler = GeocodeHandler(geocodeResultObject) if not handler.results: print('Geocoder returned 0 results! Did not create output') return None # create shapefile w = shp_helper.ShpWriter('POINT', out_fc) for field in handler.fields: w.add_field(field.name, field.type, 254) # add values for values in handler.formattedResults: w.add_row(values[0], values[1:]) w.save() # project shapefile project(out_fc, handler.spatialReference) print('Created: "{}"'.format(out_fc)) return out_fc else: raise TypeError('{} is not a {} object!'.format( geocodeResultObject, GeocodeResult))
def exportReplica(replica, out_folder): """converts a restapi.Replica() to a Shapefiles replica -- input restapi.Replica() object, must be generated from restapi.FeatureService.createReplica() out_folder -- full path to folder location where new files will be stored. """ if not hasattr(replica, 'replicaName'): print( 'Not a valid input! Must be generated from restapi.FeatureService.createReplica() method!' ) return # attachment directory and gdb set up att_loc = os.path.join(out_folder, 'Attachments') if not os.path.exists(att_loc): os.makedirs(att_loc) # set schema and create feature classes for layer in replica.layers: # download attachments att_dict = {} for attInfo in layer.attachments: out_file = assign_unique_name(os.path.join(att_loc, attInfo[NAME])) with open(out_file, 'wb') as f: f.write(urllib.request.urlopen(attInfo['url']).read()) att_dict[attInfo['parentGlobalId']] = out_file.strip() if layer.features: # make new feature class sr = layer.spatialReference out_fc = validate_name( os.path.join(out_folder, layer.name + '.shp')) g_type = G_DICT[layer.geometryType] # add all fields layer_fields = [ f for f in layer.fields if f.type not in (SHAPE, OID) ] w = shp_helper.ShpWriter(g_type, out_fc) guid = None field_map = [] for fld in layer_fields: field_name = fld.name.split('.')[-1][:10] field_type = SHP_FTYPES[fld.type] if fld.type == GLOBALID: guid = fld.name field_length = str(fld.length) if fld.length else "50" w.add_field(field_name, field_type, field_length) field_map.append((fld.name, field_name)) w.add_field('ATTCH_PATH', 'C', '254') # search cursor to write rows s_fields = [f[0] for f in field_map] date_indices = [ i for i, f in enumerate(layer_fields) if f.type == DATE_FIELD ] for feature in layer.features: row = [feature[ATTRIBUTES][f] for f in s_fields] if guid: row += [att_dict[feature[ATTRIBUTES][guid]]] for i in date_indices: row[i] = mil_to_date(row[i]) g_type = G_DICT[layer.geometryType] if g_type == 'Polygon': geom = feature[GEOMETRY][RINGS] elif g_type == 'Polyline': geom = feature[GEOMETRY][PATHS] elif g_type == 'Point': geom = [feature[GEOMETRY][X], feature[GEOMETRY][Y]] else: # multipoint - to do pass w.add_row(geom, [v if v else ' ' for v in row]) w.save() print('Created: "{0}"'.format(out_fc)) # write projection file project(out_fc, sr) return out_folder
def exportFeatureSet(out_fc, feature_set, outSR=None): """export features (JSON result) to shapefile or feature class Required: out_fc -- output feature class or shapefile feature_set -- JSON response (feature set) obtained from a query Optional: outSR -- optional output spatial reference. If none set, will default to SR of result_query feature set. """ # validate features input (should be list or dict, preferably list) if isinstance(feature_set, basestring): try: feature_set = json.loads(feature_set) except: raise IOError('Not a valid input for "features" parameter!') if not isinstance(feature_set, dict) or not FEATURES in feature_set: raise IOError('Not a valid input for "features" parameter!') # make new shapefile fields = [Field(f) for f in feature_set[FIELDS]] if not outSR: sr_dict = feature_set[SPATIAL_REFERNCE] if LATEST_WKID in sr_dict: outSR = int(sr_dict[LATEST_WKID]) else: outSR = int(sr_dict[WKID]) g_type = feature_set[GEOMETRY_TYPE] # add all fields w = shp_helper.ShpWriter(G_DICT[g_type].upper(), out_fc) field_map = [] for fld in fields: if fld.type not in [OID, SHAPE] + SKIP_FIELDS.keys(): if not any([ 'shape_' in fld.name.lower(), 'shape.' in fld.name.lower(), '(shape)' in fld.name.lower(), 'objectid' in fld.name.lower(), fld.name.lower() == 'fid' ]): field_name = fld.name.split('.')[-1][:10] field_type = SHP_FTYPES[fld.type] field_length = str(fld.length) if fld.length else "50" w.add_field(field_name, field_type, field_length) field_map.append((fld.name, field_name)) # search cursor to write rows s_fields = [fl for fl in fields if fl.name in [f[0] for f in field_map]] for feat in feature_set[FEATURES]: row = Row(feat, s_fields, outSR, g_type).values w.add_row(row[-1], [v if v else ' ' for v in row[:-1]]) w.save() print('Created: "{0}"'.format(out_fc)) # write projection file project(out_fc, outSR) return out_fc