本文整理汇总了Python中shapely.wkt.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: reassign_spatial_geometry
def reassign_spatial_geometry(instance):
coords = list(instance.geometry.coords)
if type(coords[0]) == float:
coords = [coords]
else:
while (type(coords[0][0]) != float):
coords = coords[0]
coords = [list(x) for x in coords]
for point in coords:
if point[0] >= -180 and point[0] <= 180:
return
while coords[0][0] < -180:
for point in coords:
point[0] += 360
while coords[0][0] > 180:
for point in coords:
point[0] -= 360
geometry = []
for point in coords:
latlng = [point[0], point[1]]
geometry.append(tuple(latlng))
if len(geometry) > 1:
if geometry[0] == geometry[-1]:
instance.geometry = dumps(Polygon(geometry))
else:
instance.geometry = dumps(LineString(geometry))
else:
instance.geometry = dumps(Point(geometry))
开发者ID:mikael19,项目名称:cadasta-platform,代码行数:28,代码来源:models.py
示例2: set_spatial_ranking
def set_spatial_ranking(geometry):
"""Given that we have a spatial query in ogc:Filter we check the type of geometry
and set the ranking variables"""
if util.ranking_enabled:
if geometry.type in ['Polygon', 'Envelope']:
util.ranking_pass = True
util.ranking_query_geometry = geometry.wkt
elif geometry.type in ['LineString', 'Point']:
from shapely.geometry.base import BaseGeometry
from shapely.geometry import box
from shapely.wkt import loads,dumps
ls = loads(geometry.wkt)
b = ls.bounds
if geometry.type == 'LineString':
tmp_box = box(b[0],b[1],b[2],b[3])
tmp_wkt = dumps(tmp_box)
if tmp_box.area > 0:
util.ranking_pass = True
util.ranking_query_geometry = tmp_wkt
elif geometry.type == 'Point':
tmp_box = box((float(b[0])-1.0),(float(b[1])-1.0),(float(b[2])+1.0),(float(b[3])+1.0))
tmp_wkt = dumps(tmp_box)
util.ranking_pass = True
util.ranking_query_geometry = tmp_wkt
开发者ID:dodobas,项目名称:pycsw,代码行数:25,代码来源:fes.py
示例3: get_coordinates_dump
def get_coordinates_dump(data):
if 'coordinates' in data and type(data['coordinates']) is dict:
point = data['coordinates']
if all(key in point for key in ('lat', 'lng')):
point = Point(float(point['lng']), float(point['lat']))
return dumps(point)
elif all(key in data for key in ('latitude', 'longitude')):
point = Point(float(data['longitude']), float(data['latitude']))
return dumps(point)
开发者ID:wayne-abarquez,项目名称:csitewalk,代码行数:9,代码来源:services.py
示例4: geojson_validator
def geojson_validator(value):
if value:
try:
gjson = json.loads(value)
shape = asShape(gjson)
wkt.dumps(shape)
except:
raise Invalid(_("Invalid GeoJSON"))
return value
开发者ID:chrismajewski,项目名称:ckanext-canada,代码行数:9,代码来源:navl_schema.py
示例5: geojson_validator
def geojson_validator(value):
if value:
try:
# accept decoded geojson too
if isinstance(value, basestring):
value = json.loads(value)
shape = asShape(value)
wkt.dumps(shape)
except Exception:
raise Invalid(_("Invalid GeoJSON"))
# must store as JSON
return json.dumps(value)
return value
开发者ID:LaurentGoderre,项目名称:ckanext-canada,代码行数:13,代码来源:validators.py
示例6: gj2geom
def gj2geom(geojson):
"""
Convert a GeoJSON geometry into an OGR geometry.
"""
return ogr.CreateGeometryFromWkt(wkt.dumps(shape(geojson)))
开发者ID:GlobalFishingWatch,项目名称:DistanceRasterWorkspace,代码行数:7,代码来源:cleanup.py
示例7: parse_coordinates
def parse_coordinates(coordinates):
if coordinates is None or type(coordinates) is not dict:
return coordinates
if all(key in coordinates for key in ('lat', 'lng')):
point = Point(float(coordinates['lng']), float(coordinates['lat']))
return dumps(point)
开发者ID:wayne-abarquez,项目名称:csitewalk,代码行数:7,代码来源:forms_helper.py
示例8: main
def main(opts):
pattern = loads(open(opts.input, "r").read())
extent = loads(open(opts.extent, "r").read())
if not contains.matches(extent.relate(pattern)):
print "ERROR: pattern must be contained within the extent"
return
c = pattern.centroid
(xs, ys) = extent.boundary.xy
(minx, maxx, miny, maxy) = (min(xs) - c.x, max(xs) - c.x, min(ys) - c.y, max(ys) - c.y)
outputFile = open(opts.output, "w")
geoms = []
while len(geoms) < opts.number:
dx = random.uniform(minx, maxx)
dy = random.uniform(miny, maxy)
geom = translate(pattern, xoff=dx, yoff=dy)
if contains.matches(extent.relate(geom)):
# Check that it is within the extent
overlap = False
for g in geoms:
if intersects.matches(g.relate(geom)):
overlap = True
if overlap == False:
geoms.append(geom)
for geom in geoms:
outputFile.write(dumps(geom) + "\n")
outputFile.close()
开发者ID:ZheLI0319,项目名称:pointcloud-benchmark,代码行数:34,代码来源:generate_queries.py
示例9: import_with_fiona
def import_with_fiona(fpath, source):
"""
Use fiona to import a parcel file.
Return a list of dict objects containing WKT-formatted geometries in
addition to any metadata.
"""
shapes = []
try:
with fiona.drivers():
data = fiona.open(fpath)
for obj in data:
try:
shape = scrape_fiona_metadata(obj, source)
geom = to_shapely_obj(obj)
if geom:
shape['geom'] = dumps(geom)
shapes.append(shape)
except Exception as e:
_L.warning('error loading shape from fiona. {}'.format(e))
except Exception as e:
_L.warning('error importing file. {}'.format(e))
return shapes
开发者ID:Cachola09nick,项目名称:machine,代码行数:25,代码来源:utils.py
示例10: csv_to_neatline
def csv_to_neatline(in_file, out_file):
"""
Format a CSV file for Neatline.
"""
reader = csv.DictReader(in_file)
# Add wkt field to the CSV.
cols = reader.fieldnames + ['wkt']
writer = csv.DictWriter(out_file, cols)
writer.writeheader()
for row in reader:
lat = float(row.pop('latitude'))
lon = float(row.pop('longitude'))
# Convert degrees -> meters.
meters = degrees_to_meters(lon, lat)
# Convert to WKT.
point = ShapelyPoint(meters)
row['wkt'] = wkt.dumps(point)
writer.writerow(row)
开发者ID:davidmcclure,项目名称:hilt-2016,代码行数:26,代码来源:geotext.py
示例11: getGeometryWKT
def getGeometryWKT(self):
"""Return WKT representation of geometry"""
parts = self._getGeometryRaw().split(':')
j = '{"type": "%s", "coordinates": %s}' % (
parts[0].strip(), parts[1].strip())
d = simplejson.loads(j)
return wkt.dumps(asShape(d))
开发者ID:isawnyu,项目名称:PleiadesEntity,代码行数:7,代码来源:Location.py
示例12: procesaLineaInterna
def procesaLineaInterna(featuresExternas, featuresInternas, featuresCentroide, featureDefn):
#print "Procedemos a procesar las lineas internas"
centroides = []
for centroide in featuresCentroide:
#obtenemos la altura y el rotulo del estilo de cada centroide
for n in centroide.GetStyleString().split(','):
if n.startswith('s'):
altura = float(n.replace('s:', '').replace('g', ''))
elif n.startswith('t'):
rotulo = n.split('"')[1]
punto = centroide.GetGeometryRef()
x = punto.GetX()
y = punto.GetY()
longitudRotulo = len(rotulo)
factor = 0.15 * (altura * 3.3333)
desfaseX = longitudRotulo * factor - 0.05
punto.SetPoint(point = 0, x = x + desfaseX, y = y - 0.20)
centroides.append((rotulo, punto))
featuresProceso = featuresExternas + featuresInternas
outFeature = []
if len(featuresProceso) > 1:
geometry_out = None
for inFeature in featuresProceso:
geometry_in = inFeature.GetGeometryRef()
if geometry_out is None:
geometry_out = geometry_in
geometry_out = ogr.ForceToMultiLineString(geometry_out)
else:
geometry_out = geometry_out.Union(geometry_in)
lineasInternasShapely = loads(geometry_out.ExportToWkt())
polygonsShapely = polygonize(lineasInternasShapely)
polygonGeom = []
for polygon in polygonsShapely:
polygonGeom.append(ogr.CreateGeometryFromWkt(dumps(polygon)))
for pol in polygonGeom:
for cen in centroides:
if pol.Contains(cen[1]):
feature = ogr.Feature(featureDefn)
feature.SetGeometry(pol)
feature.SetField('rotulo', cen[0])
outFeature.append(feature.Clone())
feature.Destroy()
else:
feature = ogr.Feature(featureDefn)
geometryPoly = ogr.BuildPolygonFromEdges(ogr.ForceToMultiLineString(featuresProceso[0].GetGeometryRef()), dfTolerance = 0)
feature.SetGeometry(geometryPoly)
feature.SetField('rotulo', centroides[0][0])
outFeature.append(feature.Clone())
feature.Destroy()
return outFeature
开发者ID:fpsampayo,项目名称:utils,代码行数:59,代码来源:fxcc2shp.py
示例13: _get_wkt_from_shape
def _get_wkt_from_shape(self, shape):
if shape.type == POINT:
# shapely float precision errors break cypher matches!
wkt = dumps(shape, rounding_precision=8)
else:
wkt = shape.wkt
return wkt
开发者ID:Sapphirine,项目名称:stackexchange,代码行数:8,代码来源:plugin.py
示例14: test_wkt_locale
def test_wkt_locale(self):
# Test reading and writing
p = loads('POINT (0.0 0.0)')
self.assertEqual(p.x, 0.0)
self.assertEqual(p.y, 0.0)
wkt = dumps(p)
self.assertTrue(wkt.startswith('POINT'))
self.assertFalse(',' in wkt)
开发者ID:SIGISLV,项目名称:Shapely,代码行数:9,代码来源:test_locale.py
示例15: write_regions
def write_regions(filename, regions, duprange, lossrange):
out = util.open_stream(filename, 'w')
print >>out, '\t'.join(map(str, duprange + lossrange))
for cv, region in regions.iteritems():
coords = None; area = None
if isinstance(region, geometry.Polygon): # non-degenerate
coords = list(region.exterior.coords)
area = region.area
elif isinstance(region, geometry.LineString) or isinstance(region, geometry.Point): # degenerate
coords = list(region.coords)
area = region.area
else:
raise Exception("count vector (%s) has invalid region (%s)" % (cv, dumps(region)))
coords = dumps(region)
toks = (cv, coords, area)
print >>out, '\t'.join(map(str, toks))
out.close()
开发者ID:bzhanghmc,项目名称:dlcpar,代码行数:18,代码来源:reconscape.py
示例16: handle
def handle(self, *args, **options):
CENSUS_BLOCK_2010 = pickle.load(open(BOUNDARY_DATA + "census.p", 'rb'))
NEIGHBORHOOD = pickle.load(open(BOUNDARY_DATA + "community.p",'rb'))
NEIGHBORHOOD_INDEX = create_spatial_index(NEIGHBORHOOD)
aggregate_results = {}
for i, (aggregate_id, aggregate_shape) in \
enumerate(CENSUS_BLOCK_2010.iteritems(), 1):
# print out a nice message to know how it's going
if i % 1000 == 0:
print >> sys.stderr, 'Aggregating %i of %i' % \
(i, len(CENSUS_BLOCK_2010))
if not CensusBlocks.objects.filter(census_id=aggregate_id,
building_subtype="All").exists():
print >> sys.stderr, "Updating census_id: %s" %(aggregate_id)
neighborhood_count = 0
for j,item_2010 in enumerate(NEIGHBORHOOD_INDEX.intersection(aggregate_shape.bounds,
objects=True)):
# get the element id
raw_id = item_2010.object
# get the shape from the shape dictionary
raw_shape = NEIGHBORHOOD[raw_id]
# calculate the intersection of the polygons
intersection = aggregate_shape.intersection(raw_shape)
# calculate the fraction of the area of the aggregate shape that
# is in the raw shape
frac_raw = float(intersection.area) / aggregate_shape.area
# fix rawid in those two cases for mckliney and ohare
raw_id = raw_id.title()
if raw_id == 'Mckinley Park':
raw_id = 'McKinley Park'
elif raw_id == 'Ohare':
raw_id = "O'hare"
# if there is any area above tolerance, then add it up
if neighborhood_count == 0:
neighborhood, created = Neighborhoods.objects.get_or_create(name = raw_id)
census_block, created = CensusBlocks.objects.get_or_create(census_id=aggregate_id,
building_type="Residential",
building_subtype="All",
neighborhood = neighborhood,
shape = wkt.dumps(aggregate_shape))
neighborhood_count += 1
else:
continue
开发者ID:Chicago,项目名称:ChicagoEnergy,代码行数:57,代码来源:put_in_all_census_shapes.py
示例17: write_wkt
def write_wkt(filepath, shply_geom):
"""
:param filepath: output path for new javascript file
:param shply_geom: shapely geometry features
:return:
"""
with open(filepath, "w") as f:
# create a javascript variable called ply_data used in html
# Shapely dumps geometry out to WKT
f.write("var ply_data = '" + dumps(shply_geom) + "'")
开发者ID:Algotricx,项目名称:python-geospatial-analysis-cookbook,代码行数:11,代码来源:utils.py
示例18: insert
def insert(cursor, feature, tablename, srid):
"""
Insert a "feature" as a row in PostGIS
"""
fields = ", ".join([field for field in feature["properties"].keys()])
values = ", ".join(["'%s'" % unicode(field) for field in feature["properties"].values()])
sql = """
INSERT INTO %s (%s, geom)
VALUES (%s, ST_GeomFromText('%s', %s))
""" % (tablename, fields, values, dumps(get_geom(feature)), srid)
cursor.execute(sql)
开发者ID:atlefren,项目名称:geojson2pg,代码行数:11,代码来源:import.py
示例19: getMaintenanceData
def getMaintenanceData(
start_date,
end_date,
token,
sz_roads,
):
errors=[]
filters = []
filters.append({'columnName': 'transaction_date',
'operator': 'GreaterEqualThan', 'value': start_date})
filters.append({'columnName': 'transaction_date',
'operator': 'LessEqualThan', 'value': end_date})
mc_cost = getTable(
token=token,
table='mc_cost',
columns=[
'cost_group',
'activity',
'fault',
'cost_amount',
],
filters=filters,
szRoads=sz_roads,
getGeometry=True
)
mc_cost.getData()
if mc_cost.error is True:
errors.append('mc_cost: ' + mc_cost.message)
data = []
for row in mc_cost.data:
line = loads(row['values'][4])
#length = line.length
#sections = int(math.ceil(length / 200))
#sections_pc = 1 / (sections + 1)
#section = 1
#while (section <= sections):
point = line.interpolate(0.5, True)
data.append([
row['values'][0],
row['values'][1],
row['values'][2],
row['values'][3],
dumps(point, rounding_precision=0),
])
# section = section + 1
return {'data': data, 'errors': errors}
开发者ID:petehilljnr,项目名称:info-portal,代码行数:53,代码来源:rammData.py
示例20: parse_area
def parse_area(area):
if area is None:
return area
points = map(get_lng_lat_pair, area)
if len(points) == 2:
polygon = box(points[0][0], points[0][1], points[1][0], points[1][1])
else:
polygon = Polygon(points)
return dumps(polygon)
开发者ID:wayne-abarquez,项目名称:csitewalk,代码行数:12,代码来源:forms_helper.py
注:本文中的shapely.wkt.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论