Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_invalid_polygon(self):
with self.assertRaises(ValueError) as cm:
geojson.Polygon([1], validate=True)
self.assertIn("Each element of a polygon's coordinates must be a list",
str(cm.exception))
poly1 = geojson.Polygon(
[[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15)]])
self.assertEqual(poly1.is_valid, False)
poly2 = geojson.Polygon(
[[(2.38, 57.322), (23.194, -20.28),
(-120.43, 19.15), (2.38, 57.323)]])
self.assertEqual(poly2.is_valid, False)
# Compute center coordinates
x = (bounds[0][0] + bounds[2][0]) / 2.0
y = (bounds[0][1] + bounds[2][1]) / 2.0
# Use smll percentage of height & width
dx = 0.005 * (bounds[2][0] - bounds[0][0])
dy = 0.005 * (bounds[2][1] - bounds[0][1])
rect = [
[x,y], [x, y-dy], [x-dx, y-dy], [x-dx, y], [x,y]
]
# print()
# print(rect)
# Must pass rectangle in as a LIST, in order to get geom formatted the way resgeodata uses
crop_geom = geojson.Polygon([rect])
print()
print(crop_geom)
sys.exit(0)
# Perform crop operation
from gaia import preprocess
cropped_dataset = preprocess.crop(dataset, crop_geom, name='crop100m.tif')
print()
cropped_meta = cropped_dataset.get_metadata()
print('Cropped dataset width {}, height {}'.format(
cropped_meta['width'], cropped_meta['height']))
print(cropped_meta)
print('finis', dataset)
with fiona.drivers():
with fiona.open(path, 'r') as source:
for feature in source:
features.append(feature)
return FeatureCollection(features)
if fmt.lower()=='txt-bbox':
polys = []
with open(path) as f:
#skip first line which is a bunding polygon
f.readline()
for line in f:
feature_id, x1, y1, x2, y2 = line.split()
properties = {'feature_id': feature_id}
polys.append(Feature(geometry=Polygon([_bbox2poly(x1, y1, x2, y2)]), properties=properties, id=feature_id))
return FeatureCollection(polys)
raise IOError('Format not recognized: %s' % fmt)
geo_props['reference-label'] = rel_meta.label
geo_props['reference-slug'] = rel_meta.slug
else:
geo_props['reference-type'] = 'specified'
if self.assertion_hashes:
geo_props['hash_id'] = geo.hash_id
geo_props['feature_id'] = geo.feature_id
if geo.specificity < 0 and self.item_type != 'projects':
# case where we've got reduced precision geospatial data
# geotile = quadtree.encode(geo.latitude, geo.longitude, abs(geo.specificity))
geo_props['location-precision'] = abs(geo.specificity)
geo_props['location-precision-note'] = 'Location data approximated as a security precaution.'
gmt = GlobalMercator()
geotile = gmt.lat_lon_to_quadtree(geo.latitude, geo.longitude, abs(geo.specificity))
tile_bounds = gmt.quadtree_to_lat_lon(geotile)
item_polygon = Polygon([[(tile_bounds[1], tile_bounds[0]),
(tile_bounds[1], tile_bounds[2]),
(tile_bounds[3], tile_bounds[2]),
(tile_bounds[3], tile_bounds[0]),
(tile_bounds[1], tile_bounds[0])
]])
item_f_poly = Feature(geometry=item_polygon)
item_f_poly.id = geo_node_derived
item_f_poly.geometry.id = geo_node_derived_geom
item_f_poly.properties.update(geo_props)
item_f_poly.properties['location-note'] = 'This region defines the '\
'approximate location for this item.'
item_f_poly.properties['id'] = geo_node_derived_props
features_dict[geo_node_derived] = item_f_poly
item_point = Point((float(geo.longitude), float(geo.latitude)))
item_f_point = Feature(geometry=item_point)
item_f_point.id = geo_node
def to_geojson(df):
"""Converts a dataframe to a geojson object.
Args:
df (dataframe): A dataframe that is being converted to a geojson object.
Returns:
A geojson object is what is being returned.
"""
_func = {
'LineString': LineString,
'Point': Point,
'Polygon': Polygon,
}
features = []
if not df.empty:
# TODO what is this code doing and is it now obsolete with the new DB?
idx = df.columns.str.startswith('_')
r = {field: field[1:] for field in df.columns[idx]}
for uid, row in df.iterrows():
metadata = json.loads(row[~idx].dropna().to_json())
row = row[idx].rename(index=r)
# create geojson geometry
geometry = None
if row['geom_type'] is not None:
coords = row['geom_coords']
if not isinstance(coords, (list, tuple)):
coords = json.loads(coords)
features = []
campaign_aois = campaign_geojson['features']
logging.info('Campaign has {0} geometries'.format(len(campaign_aois)))
for index, poly in enumerate(campaign_aois):
# Fix right-hand rule.
polygon = sp.Polygon(poly['geometry']['coordinates'][0])
polygon = sp.polygon.orient(polygon)
# To get just a small number of tiles around.
scaled_polygon = scale(polygon, 1.1, 1.1)
# Create geojson.
feature = gj.Feature(
geometry=gj.Polygon([list(polygon.exterior.coords)]),
properties={"id": index, "parent": None}
)
features.append(feature)
event = {'bbox': scaled_polygon.bounds,
'campaign_uuid': uuid,
'index': index,
'zoom_levels': zoom_levels
}
# Run lambda function that fetches tiles.
spawn_fetch_tiles(event)
# Save new geojson.
tiles_file = 'tiles.geojson'
logging.info('Saving hashes to {0}'.format(tiles_file))
def create_grid_feature(box, polygon_id):
poly = sp.box(*box)
list_polygon = list(poly.exterior.coords)
# Create geojson.
feature = gj.Feature(
geometry=gj.Polygon([list_polygon]),
properties={"parent": polygon_id}
)
return feature
def from_dict(cls, area_poly: dict):
""" Create a new Priority Area from dictionary """
pa_geojson = geojson.loads(json.dumps(area_poly))
if type(pa_geojson) is not geojson.Polygon:
raise InvalidGeoJson("Priority Areas must be supplied as Polygons")
is_valid_geojson = geojson.is_valid(pa_geojson)
if is_valid_geojson["valid"] == "no":
raise InvalidGeoJson(
f"Priority Area: Invalid Polygon - {is_valid_geojson['message']}"
)
pa = cls()
valid_geojson = geojson.dumps(pa_geojson)
pa.geometry = ST_SetSRID(ST_GeomFromGeoJSON(valid_geojson), 4326)
return pa
def geometry(self):
try:
if self.type() == 'node':
if not self.lon() or not self.lat():
self._raiseException('Cannot build geometry: geometry information not included.')
return geojson.Point((self.lon(), self.lat()))
elif self.type() == 'way':
if not self.__getElement('geometry'):
self._raiseException('Cannot build geometry: geometry information not included.')
cs = self.__geometry_csToList(self.__getElement('geometry'))
if self.__geometry_equal(cs[0], cs[-1]):
return geojson.Polygon([cs])
else:
return geojson.LineString(cs)
elif self.type() == 'relation':
members = copy.deepcopy(self.__members())
membersOuter = self.__geometry_extract(members, 'outer')
if len(membersOuter) == 0:
self._raiseException('Cannot build geometry: no outer rings found.')
membersInner = self.__geometry_extract(members, 'inner')
ringsOuter = self.__geometry_buildRings(membersOuter)
ringsInner = self.__geometry_buildRings(membersInner)
ringsOuter = self.__geometry_orientRings(ringsOuter, positive=True)
ringsInner = self.__geometry_orientRings(ringsInner, positive=False)
polygons = self.__geometry_buildPolygons(ringsOuter, ringsInner)
if len(polygons) > 1:
return geojson.MultiPolygon(polygons)
else: