本文整理汇总了Python中geojson.dumps方法的典型用法代码示例。如果您正苦于以下问题:Python geojson.dumps方法的具体用法?Python geojson.dumps怎么用?Python geojson.dumps使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类geojson
的用法示例。
在下文中一共展示了geojson.dumps方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: do_features_list
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def do_features_list(table):
"""Handle the parsing of the request and return the geojson.
This routes all the /tables/... requests to the handler.
See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route
Args:
database: The name of the database to use, this is picked from the URL.
table: The database table to query from, this is picked from the URL.
Returns:
A flask.Response object with the GeoJSON to be returned, or an error JSON.
"""
where = flask.request.args.get('where', default='true')
select = flask.request.args.get('select', default='')
limit = flask.request.args.get('limit')
order_by = flask.request.args.get('orderBy')
intersects = flask.request.args.get('intersects')
offset = flask.request.args.get('offset')
result = flask.g.features.list(table, select, where,
limit=limit, offset=offset, order_by=order_by,
intersects=intersects)
return build_response(result, geojson.dumps)
示例2: _render_feature_collection
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def _render_feature_collection(feature_collection, geojson_filepath, strdump, serialize):
if not serialize:
return feature_collection
if strdump or not geojson_filepath:
return geojson.dumps(feature_collection, sort_keys=True, separators=(',', ':'))
with open(geojson_filepath, 'w') as fileout:
geojson.dump(feature_collection, fileout, sort_keys=True, separators=(',', ':'))
示例3: encode
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def encode(geom: SlfGeometry) -> Optional[str]:
"""
Convert the given Simple Location Format shape to the corresponding
GeoJSON shape.
:param geom: the Simple Location Format shape to convert.
:return: the GeoJSON as a string if the input shape is of a known type;
``None`` otherwise.
"""
geo_json_rep = lookup_encoder(geom)(geom)
if geo_json_rep:
return dumps(geo_json_rep, sort_keys=True)
return None
示例4: __init__
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def __init__(self, objConverter, header='[', footer=']',
jsonDumpser=json.dumps):
self.objConverter = objConverter
self.header = header
self.footer = footer
self.jsonDumpser = json.dumps
示例5: build_response
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def build_response(result, method=json.dumps):
status = 200
if 'status' in result:
status = result['status']
if 'error' in result:
method = json.dumps
if status is None:
status = 500
return flask.Response(
response=method(result),
mimetype='application/json',
status = status)
示例6: do_pip
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def do_pip(database, table):
"""Handle the parsing of the point in polygon request and return a polygon.
This routes all the /pip/... requests to the handler.
See http://flask.pocoo.org/docs/0.10/api/#flask.Flask.route
Args:
database: The name of the database to use, this is picked from the URL.
table: The database table to query from, this is picked from the URL.
Returns:
A flask.Response object with the GeoJSON to be returned, or an error JSON.
"""
lat = float(flask.request.args.get('lat', default=0.0))
lng = float(flask.request.args.get('lng', default=0.0))
select = flask.request.args.get('select', default='')
try:
pip = PointInPolygon(_INSTANCE, database, table)
except MySQLdb.OperationalError as e:
error = {'error': 'Database Error %s' % str(e)}
return flask.Response(
response=json.dumps(error),
mimetype='application/json',
status=500)
polygon = pip.pip(lat, lng, select)
if 'error' in polygon:
return flask.Response(
response=json.dumps(polygon),
mimetype='application/json',
status=500)
else:
return flask.Response(
response=geojson.dumps(polygon, sort_keys=True),
mimetype='application/json',
status=200)
示例7: export
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def export(self, filename):
""" Export GeoJSON object to file
Input: filename
Output: written file
"""
f = open(filename, 'w')
f.writelines(geojson.dumps(self.geojson))
f.close()
示例8: create_map
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def create_map(model=None, filename=None):
"""
export model as a geojson object
"""
import geojson
if filename is None:
filename = f'{model.name}.html'
if model.crs:
model.to_crs("+init=EPSG:4326")
else:
raise ValueError('Model object must have a valid crs')
# get map centroid and bbox
c, bbox = centroid_and_bbox_from_coords(model.inp.coordinates)
# start writing that thing
with open(BETTER_BASEMAP_PATH, 'r') as bm:
with open(filename, 'w') as newmap:
for line in bm:
if 'INSERT GEOJSON HERE' in line:
newmap.write(f'conduits = {geojson.dumps(model.links.geojson)}\n')
newmap.write(f'nodes = {geojson.dumps(model.nodes.geojson)}\n')
elif '// INSERT MAP CENTER HERE' in line:
newmap.write('\tcenter:[{}, {}],\n'.format(c[0], c[1]))
elif '// INSERT BBOX HERE' in line and bbox is not None:
newmap.write('\tmap.fitBounds([[{}, {}], [{}, {}]]);\n'
.format(bbox[0], bbox[1], bbox[2],
bbox[3]))
else:
newmap.write(line)
示例9: df_to_geojson
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def df_to_geojson(df, properties=None, lat='lat', lon='lon', precision=6, date_format='epoch', filename=None):
"""Serialize a Pandas dataframe to a geojson format Python dictionary / file
"""
if not properties:
# if no properties are selected, use all properties in dataframe
properties = [c for c in df.columns if c not in [lon, lat]]
for prop in properties:
# Check if list of properties exists in dataframe columns
if prop not in list(df.columns):
raise ValueError(
'properties must be a valid list of column names from dataframe')
if prop in [lon, lat]:
raise ValueError(
'properties cannot be the geometry longitude or latitude column')
# convert dates/datetimes to preferred string format if specified
df = convert_date_columns(df, date_format)
if filename:
with open(filename, 'w') as f:
# Overwrite file if it already exists
pass
with open(filename, 'a+') as f:
# Write out file to line
f.write('{"type": "FeatureCollection", "features": [\n')
# Iterate over enumerated iterrows as index from iterrows alone could be non-sequential
for i, (index, row) in enumerate(df[[lon, lat] + properties].iterrows()):
if i == 0:
f.write(geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
else:
f.write(',' + geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
f.write(']}')
return {
"type": "file",
"filename": filename,
"feature_count": df.shape[0]
}
else:
features = []
df[[lon, lat] + properties].apply(lambda x: features.append(
row_to_geojson(x, lon, lat, precision, date_format)), axis=1)
return geojson.FeatureCollection(features)
示例10: saveOsmData
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def saveOsmData(query) :
result = api.query(query)
for way in result.ways:
# "leisure=pitch,sport=" , don't use "-" char" in featureDirectoryName
featureDirectoryName = way.tags.get("sport")
outputDirectoryName = os.path.join(cfg.rootOsmDir,featureDirectoryName)
if ( os.path.exists(outputDirectoryName) == False):
os.makedirs(outputDirectoryName)
if ( (featureDirectoryName in summary) == False) :
summary[featureDirectoryName] = 1
else:
summary[featureDirectoryName] += 1
filenameBase= os.path.join(cfg.rootOsmDir,featureDirectoryName,str(way.id))
#print("Name: %d %s %s" % ( way.id ,way.tags.get("name", ""),filenameBase))
# leave the csv file for now, will delete when the script for the next
# stage is rewritten.
with open("%s.csv" % (filenameBase), "wt") as text_file:
for node in way.nodes:
text_file.write("%0.7f\t%0.7f\n" % (node.lat, node.lon))
with open("%s.GeoJSON" % (filenameBase), "wt") as text_file:
rawNodes = []
for node in way.nodes:
rawNodes.append( (node.lon, node.lat) )
try:
geom = shapely.geometry.Polygon(rawNodes)
tags = way.tags
tags['wayOSMId'] = way.id
features =[]
features.append( geojson.Feature(geometry=geom, properties=tags))
featureC = geojson.FeatureCollection(features)
text_file.write(geojson.dumps(featureC))
except Exception as e:
print(e)
示例11: write
# 需要导入模块: import geojson [as 别名]
# 或者: from geojson import dumps [as 别名]
def write(self, rpt_dir):
#write cost per sewer segment spreadsheet
self.newconduits.to_csv(os.path.join(rpt_dir,'cost_estimate.csv'))
self.flood_comparison.to_csv(os.path.join(rpt_dir,'parcel_flood_comparison.csv'))
#write parcel json files
parcels = spatial.read_shapefile(sg.config.parcels_shapefile)
parcels = parcels[['PARCELID', 'ADDRESS', 'OWNER1', 'coords']]
flooded = self.flood_comparison
flooded = flooded.loc[flooded.Category.notnull()] #parcels with significant flood delta
flooded = pd.merge(flooded, parcels, right_on='PARCELID', left_index=True)
colors = flooded.apply(lambda row:'#%02x%02x%02x' % drawing.parcel_draw_color(row, style='delta'), axis=1)
flooded = flooded.assign(fill=colors)
geoparcelpath = os.path.join(rpt_dir,'delta_parcels.json')
spatial.write_geojson(flooded, filename=geoparcelpath, geomtype='polygon')
#write new conduit json, shapefiles
shpdir = os.path.join(os.path.dirname(rpt_dir), 'shapefiles')
if not os.path.exists(shpdir):os.mkdir(shpdir)
geocondpath = os.path.join(rpt_dir,'new_conduits.json')
shpcondpath = os.path.join(shpdir, self.alt_report.model.inp.name + '_new_conduits.shp')
spatial.write_geojson(self.newconduits, filename=geocondpath)
spatial.write_shapefile(self.newconduits, filename=shpcondpath)
#write node and conduit report csvs
self.alt_report.model.nodes().to_csv(os.path.join(rpt_dir,'nodes.csv'))
self.alt_report.model.conduits().to_csv(os.path.join(rpt_dir,'conduits.csv'))
#write a html map
with open (geocondpath, 'r') as f:
geo_conduits = geojson.loads(f.read())
proposed_flooded = self.alt_report.parcel_flooding
proposed_flooded = pd.merge(proposed_flooded, parcels, right_on='PARCELID', left_index=True)
geo_parcels = spatial.write_geojson(proposed_flooded)
# with open (geoparcelpath, 'r') as f:
# geo_parcels = geojson.loads(f.read())
with open(BETTER_BASEMAP_PATH, 'r') as bm:
filename = os.path.join(os.path.dirname(geocondpath), self.alt_report.model.name + '.html')
with open(filename, 'wb') as newmap:
for line in bm:
if '//INSERT GEOJSON HERE ~~~~~' in line:
newmap.write('conduits = {};\n'.format(geojson.dumps(geo_conduits)))
newmap.write('nodes = {};\n'.format(0))
newmap.write('parcels = {};\n'.format(geojson.dumps(geo_parcels)))
else:
newmap.write(line)
#create figures