本文整理汇总了Python中shapely.wkt.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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
示例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)
示例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
示例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
示例6: gj2geom
def gj2geom(geojson):
"""
Convert a GeoJSON geometry into an OGR geometry.
"""
return ogr.CreateGeometryFromWkt(wkt.dumps(shape(geojson)))
示例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)
示例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()
示例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
示例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)
示例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))
示例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
示例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
示例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)
示例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()