Exemplo n.º 1
0
 def test_invalid_polygon(self):
     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)
    def model_geometry(self, target_epsg=4326, layer=0):

        i_bound = self.get_ibound()
        if layer >= len(i_bound):
            raise Exception('Layer with key ' + str(layer) +
                            'not found. Max: ' + str(len(i_bound)))

        layer = i_bound[layer]
        mask = np.array(np.ma.masked_values(layer, 1, shrink=False),
                        dtype=bool)
        mpoly_cells = []
        for vec in rasterio.features.shapes(layer, mask=mask):
            mpoly_cells.append(geojson.Polygon(vec[0]["coordinates"]))

        mpoly_cells = mpoly_cells[0]
        mpoly_coordinates_utm = geojson.utils.map_tuples(
            lambda c: self.get_cell_center(c), mpoly_cells)

        tf = Transformer.from_crs(int(self.modelgrid.epsg),
                                  int(target_epsg),
                                  always_xy=True,
                                  skip_equivalent=True)
        mpoly_coordinates_target = geojson.utils.map_tuples(
            lambda c: self.transform(tf, c), mpoly_coordinates_utm)

        # noinspection PyTypeChecker
        polygon = geojson.Polygon(mpoly_coordinates_target['coordinates'])
        return polygon
Exemplo n.º 3
0
 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:
                 return geojson.Polygon(polygons[0])
         else:
             self._raiseException('Cannot build geometry: type of element unknown.')
     except Exception as e:
         _extendAndRaiseException(e, ' ({}/{})'.format(self.type(), self.id()))
Exemplo n.º 4
0
def main(args):
    features = []

    if args.equator:
        geom = geojson.LineString([[-180, 0], [180, 0]])
        features.append(geojson.Feature('equator', geom))

    if args.tropics:
        cancer = geojson.LineString([[-180, 23.4378], [180, 23.4368]])
        features.append(geojson.Feature('cancer', cancer))

        capricorn = geojson.LineString([[-180, -23.4378], [180, -23.4378]])
        features.append(geojson.Feature('capricorn', capricorn))

    if args.lat:
        for top, right, bottom, left in latBand(args.lat):
            geom = geojson.Polygon([[top, left], [top, right], [bottom, right],
                                    [bottom, left]])

            features.append(geojson.Feature(geometry=geom))

    if args.long:
        for top, right, bottom, left in longBand(args.long):
            geom = geojson.Polygon([[top, left], [top, right], [bottom, right],
                                    [bottom, left]])

            features.append(geojson.Feature(geometry=geom))

    collection = geojson.FeatureCollection(features, indent=2)

    print geojson.dumps(collection)
Exemplo n.º 5
0
 def test_invalid_polygon(self):
     poly1 = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28),
                               (-120.43, 19.15)]])
     self.assertEqual(is_valid(poly1)['valid'], NO)
     poly2 = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28),
                               (-120.43, 19.15), (2.38, 57.323)]])
     self.assertEqual(is_valid(poly2)['valid'], NO)
Exemplo n.º 6
0
def boundJson(x,y, geometryType = 1, inProjection = 'epsg:4326' ,outProjection = 'epsg:3857'):
    """
    Create a GeoJSON boundary from csv input
    Args:
        filename(file): the filename to perform the operation on
        geometryType(int): type of geometric shape, 1 = rectangular, 2 = circular, 3 = irregular
        inProjection(int): EPSG projection number for csv data
        outProjection(int): EPSG projection number for output GeoJSON string (default 3857 for google maps)

    Returns:
        GeoJSON string of polygon boundary 
    """
    g = geometryType
    inP = inProjection
    outP = outProjection
    jFeat = []
    crs = {
    "type": "name",
    "properties": {
        "name": outP
        }}

    inP = pyproj.Proj(init=inP)
    outP = pyproj.Proj(init=outP)


    #get the point coordinates
    points = np.column_stack([x,y])

    if g == 1:
        xMax = [x.max(),y[np.where(x==x.max())].item(0)]
        xMax = list(pyproj.transform(inP,outP,xMax[0],xMax[1]))

        yMax = [x[np.where(y==y.max())].item(0),y.max()]
        yMax = list(pyproj.transform(inP,outP,yMax[0],yMax[1]))

        xMin = [x.min(),y[np.where(x==x.min())].item(0)]
        xMin = list(pyproj.transform(inP,outP,xMin[0],xMin[1]))

        yMin = [x[np.where(y==y.min())].item(0),y.min()]
        yMin = list(pyproj.transform(inP,outP,yMin[0],yMin[1]))

        geoJson = geojson.Polygon([[xMax,yMax,xMin,yMin,xMax]],crs=crs)

    if g == 2 or g == 3:
        points = MultiPoint(points)
        m = mapping(points.convex_hull)
        for i in m['coordinates']:
            for j in i:
                jFeat.append(pyproj.transform(inP,outP,j[0],j[1]))

        geoJson = geojson.Polygon([jFeat], crs= crs)

    #return geoJson
    return geojson.loads(geojson.dumps(geoJson))#, points
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
def shapefile_to_geojson(shp_file, p=None):
    #input: shapefile name, index name, document type, OPTIONAL pyproj projection
    #output: geojson feature collection

    ###ONLY WORKS FOR SINGLE TYPE SHAPEFILE####

    sf = shapefile.Reader(shp_file)
    features = []
    recs = sf.iterRecords()
    for shape in sf.iterShapes():
        rec = recs.next()
        props = {k: v for k, v in zip([f[0] for f in sf.fields[1:]], rec)}
        zipcode = props['ZCTA5CE10']
        if p:
            coords = [p(x, y, inverse=True) for x, y in shape.points]
        else:
            coords = [(lng, lat) for lng, lat in shape.points]

        if shape.shapeType == 1:
            features.append(
                geojson.Feature(geometry=geojson.Point(coords[0]),
                                properties={'zipcode': zipcode}))

        if shape.shapeType == 3:
            features.append(
                geojson.Feature(geometry=geojson.LineString(coords),
                                properties={'zipcode': zipcode}))

        if shape.shapeType == 5:
            if len(shape.parts) == 1:
                geom = geojson.Polygon([[(pt1, pt2) for pt1, pt2 in coords]])
                features.append(
                    geojson.Feature(geometry=geom,
                                    properties={'zipcode': zipcode}))
            else:
                for i in range(len(shape.parts)):
                    if i < len(shape.parts) - 1:
                        part = coords[shape.parts[i]:shape.parts[i + 1]]
                    else:
                        part = coords[shape.parts[-1]:]

                    geom = geojson.Polygon([[(pt1, pt2) for pt1, pt2 in part]])
                    feat = geojson.Feature(
                        geometry=geom,
                        properties={'zipcode': zipcode + '-' + str(i + 1)})

                    features.append(feat)

    return geojson.FeatureCollection(features)
Exemplo n.º 9
0
    def __init__(self, geom_type, zoom, m):
        proj = mapnik.Projection(m.srs)
        width_of_world_in_pixels = 2**zoom * 256
        width_of_world_in_metres = proj.forward(mapnik.Coord(
            180, 0)).x - proj.forward(mapnik.Coord(-180, 0)).x
        width_of_image_in_metres = float(
            m.width) / width_of_world_in_pixels * width_of_world_in_metres
        height_of_image_in_metres = float(
            m.height) / width_of_world_in_pixels * width_of_world_in_metres

        self.max_x = width_of_image_in_metres
        self.max_y = height_of_image_in_metres
        self.min_x = 0
        self.min_y = 0

        if geom_type == "point":
            self.geom = geojson.Point((self.max_x / 2, self.max_y / 2))
        elif geom_type == "point75":
            self.geom = geojson.Point((self.max_x * 0.5, self.max_y * 0.75))
        elif geom_type == "polygon":
            self.geom = geojson.Polygon([[(0, 0), (self.max_x, 0),
                                          (self.max_x, self.max_y),
                                          (0, self.max_y), (0, 0)]])
        elif geom_type == "linestring-with-gap":
            self.geom = geojson.MultiLineString([[
                (0, 0.5 * self.max_y), (self.max_x * 0.45, 0.5 * self.max_y),
                (self.max_x * 0.55, 0.5 * self.max_y),
                (self.max_x, 0.5 * self.max_y)
            ]])
        elif geom_type == "polygon-with-hole":
            self.geom = geojson.Polygon([[[0.7 * self.max_x, 0.2 * self.max_y],
                                          [0.9 * self.max_x, 0.9 * self.max_y],
                                          [0.3 * self.max_x, 0.8 * self.max_y],
                                          [0.2 * self.max_x, 0.4 * self.max_y],
                                          [0.7 * self.max_y,
                                           0.2 * self.max_y]],
                                         [[0.4 * self.max_x, 0.6 * self.max_y],
                                          [0.7 * self.max_x, 0.7 * self.max_y],
                                          [0.6 * self.max_x, 0.4 * self.max_y],
                                          [0.4 * self.max_x,
                                           0.6 * self.max_y]]])
        elif geom_type == "linestring":
            self.geom = geojson.LineString([[0, 0.5 * self.max_y],
                                            [self.max_x, 0.5 * self.max_y]])
        else:
            raise MapnikLegendaryError(
                "Geometry type {} is not supported for legend entries.".format(
                    geom_type))
Exemplo n.º 10
0
    def _add_polygon(self):
        """
        Computes polygon, removes water bodies, and stores.
        """

        # Get points without outliers.
        fpoints = list(
            zip(
                self.data.loc[~self.data.outlier_status, "decimalLongitude"],
                self.data.loc[~self.data.outlier_status, "decimalLatitude"],
            ))

        # Get convex hull around points.
        rawpoly = shapely.geometry.Polygon(fpoints)
        conv_hull = rawpoly.convex_hull

        # Get intersection with global LAND to remove water bodies.
        clean_hull = conv_hull.intersection(LAND)

        # Store [Multi]Polygon as the geographic range.
        self.georange = clean_hull

        # If the resulting shape is a single Polygon, write it.
        if clean_hull.geom_type == "Polygon":
            outline = clean_hull.boundary.coords
            coords = list(zip(outline.xy[0], outline.xy[1]))
            geometry = geojson.Polygon(coordinates=[coords], validate=True)
            feature = geojson.Feature(geometry=geometry,
                                      properties={"type": "geographic_range"})

        # For a MultiPolygon, combine the pieces one at a time.
        elif clean_hull.geom_type == "MultiPolygon":
            geometry = geojson.MultiPolygon()
            for poly in clean_hull:
                coords = list(
                    zip(
                        poly.boundary.coords.xy[0],
                        poly.boundary.coords.xy[1],
                    ))
                subgeometry = geojson.Polygon([coords], validate=True)
                geometry.coordinates.append(subgeometry.coordinates)
            feature = geojson.Feature(geometry=geometry,
                                      properties={"type": "geographic_range"})
        else:
            raise ValueError(f"odd shaped hull error: {clean_hull.geom_type}")

        # Append to feature collection.
        self.feature_collection['features'].append(feature)
Exemplo n.º 11
0
    def __get_polygon_from_feature(self, raw_polygon):
        """translate the shapely polygon format to geojson, and also from utm coordinate to Geographic coordinate

        Args:
            raw_polygon (shapely.polygon): polygons in shapely format

        Returns:
            geojson.Feature: geojson format polygon
        """
        raw_contour = np.array(list(raw_polygon.exterior.coords))

        # add utm coordinate to the data. Don't ask me how I translated it.
        raw_contour[:, 0] /= 100.0
        raw_contour[:, 0] += self.pre_processor.min_east * 100
        raw_contour[:, 1] /= 100.0
        raw_contour[:, 1] += self.pre_processor.min_north * 100

        # translate utm to geographic
        raw_geo = utm.to_latlon(raw_contour[:, 0], raw_contour[:, 1], 10, "U")
        geo_points = np.vstack((raw_geo[1], raw_geo[0])).T
        polygon = geojson.Polygon([geo_points.tolist()])
        polygon_feature = geojson.Feature(geometry=polygon)
        polygon_feature["properties"]["id"] = "L-YEAR" + str(uuid.uuid4())

        return polygon_feature
Exemplo n.º 12
0
def _geojson_poly_from_wkt(wkt):
    """Return a geojson Polygon object from a WKT string"""
    coordlist = re.search(r'\(\s*([^()]+)\s*\)', wkt).group(1)
    coord_list_split = (coord.split(' ') for coord in coordlist.split(','))
    poly = geojson.Polygon([(float(coord[0]), float(coord[1]))
                            for coord in coord_list_split])
    return poly
Exemplo n.º 13
0
Arquivo: geo.py Projeto: nbashev/noc
def get_bbox(x0: float, x1: float, y0: float, y1: float) -> geojson.Polygon:
    """
    Get normalized bounding box
    :param x0:
    :param x1:
    :param y0:
    :param y1:
    :return:
    """

    def bound_x(x):
        return max(min(x, 180), -180)

    def bound_y(y):
        return max(min(y, 90), -90)

    x0 = bound_x(x0)
    x1 = bound_x(x1)
    y0 = bound_y(y0)
    y1 = bound_y(y1)

    if x1 < x0:
        x0, x1 = x1, x0
    if y1 < y0:
        y0, y1 = y1, y0

    return geojson.Polygon([[[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]])
Exemplo n.º 14
0
    def test_valid_geometrycollection(self):
        point = geojson.Point((10, 20))
        poly = geojson.Polygon([[(2.38, 57.322), (23.194, -20.28),
                                 (-120.43, 19.15), (2.38, 57.322)]])

        geom_collection = geojson.GeometryCollection(geometries=[point, poly])
        self.assertTrue(geom_collection.is_valid)
Exemplo n.º 15
0
    def way(self, w):
        if not w.is_closed() or len(w.nodes) < 4:
            return

        if not list(
                set(["building", "construction"])
                & set([k for k in dict(w.tags).keys()])):
            return

        if "building" in w.tags and w.tags["building"] in set(
            ["houseboat", "static_caravan", "stadium", "digester", "ruins"]):
            return

        if "location" in w.tags and w.tags["location"] in set(
            ["underground", "underwater"]):
            return

        geometry = geojson.Polygon([[(n.lon, n.lat) for n in w.nodes]])
        shape = shapely.geometry.shape(geometry)

        if shape.is_valid:
            feature = geojson.Feature(geometry=geometry)
            self.features.append(feature)
        else:
            print(
                "Warning: invalid feature: https://www.openstreetmap.org/way/{}"
                .format(w.id),
                file=sys.stderr)
Exemplo n.º 16
0
def firegrid_geojson(firegrid, edges, ignore_trees=False):
    try:
        elons = edges[0].tolist()
        elats = edges[1].tolist()
    except AttributeError:
        elons = edges[0]
        elats = edges[1]

    out_rects = []
    for x in range(len(elons) - 1):
        for y in range(len(elats) - 1):
            data = firegrid[y, x]
            if data == G_TREE and ignore_trees:
                continue
            tl = (elons[x], elats[y])
            tr = (elons[x + 1], elats[y])
            bl = (elons[x], elats[y + 1])
            br = (elons[x + 1], elats[y + 1])

            # draw rectangle
            poly = [tl, bl, br, tr, tl]  # manually draw rect, ccw per spec
            rect = geojson.Polygon([poly])
            lonlat_rect = geojson.utils.map_tuples(
                lambda c: LONLAT_TF.transform(*c), rect)

            feature_rect = geojson.Feature(
                geometry=lonlat_rect,
                properties={'celltype': G_STATE[data]},
            )

            out_rects.append(feature_rect)

    out_features = geojson.FeatureCollection(out_rects)
    return out_features
Exemplo n.º 17
0
def toGeoJson(data, dtype):
    """formats all data input to valid geojson
    """
    dtype = dtype.lower()

    if dtype == "point":
        collection = []
        for i in range(0, len(data)):
            point = geojson.Point(data[i])
            collection.append(geojson.Feature(geometry=point))
        collection = geojson.FeatureCollection(collection)
        # pp.pprint(collection) # valid
        return collection

    if dtype == "polygon":
        polygon = geojson.Polygon(data)
        # print(polygon)  # valid
        return polygon

    elif dtype == "linestring":
        linestring = geojson.LineString(data)
        # print(linestring) #valid
        return (linestring)

    elif dtype == "multilinestring":
        mls = geojson.MultiLineString(data)
        # print(mls) # valid
        return mls

    else:
        print("\nBAD ARGUMENT\n")
Exemplo n.º 18
0
def write_to(data, property_names, output_file):
    '''
    Write list of tuples to geojson.
       First entry of each tuple should be geometry in hex coordinates
       and the rest properties.

       Args:
           data: List of tuples.
           property_names: List of strings. Should be same length as the
                           number of properties.
           output_file (str): Output file name.

    '''

    geojson_features = []
    for entry in data:
        coords_in_hex, properties = entry[0], entry[1:]
        geometry = loads(coords_in_hex, hex=True)
        property_dict = dict(zip(property_names, properties))
        if geometry.geom_type == 'Polygon':
            coords = [list(geometry.exterior.coords)]   # brackets required
            geojson_feature = geojson.Feature(geometry=geojson.Polygon(coords),
                                              properties=property_dict)
        elif geometry.geom_type == 'Point':
            coords = list(geometry.coords)[0]
            geojson_feature = geojson.Feature(geometry=geojson.Point(coords),
                                              properties=property_dict)
        geojson_features.append(geojson_feature)

    feature_collection = geojson.FeatureCollection(geojson_features)

    with open(output_file, 'wb') as f:
        geojson.dump(feature_collection, f)
def fillImageGeoJSON(image_data, seed_point, tolerance):
    if not(
        # note, the image_data has a shape of (rows, cols), the seed is (x, y)
        0.0 <= seed_point[0] <= image_data.shape[1] and
        0.0 <= seed_point[1] <= image_data.shape[0]
    ):
        # TODO: a proper out of bounds error
        return {'error': 'out of bounds'}

    image_mask = segmentConnectedRegion(image_data, seed_point, tolerance)
    contour = extractContour(image_mask)

    feat = geojson.Feature(
        # TODO: can this be made a LineString?
        # geometry=geojson.LineString(coordinates=tuple(contour.tolist())),
        geometry=geojson.Polygon(coordinates=(contour.tolist(),)),
        properties={
            'rgbcolor': 'rgba(255, 255, 255, 0.1)',
            'hexcolor': '#ff0000',
            'source': 'autofill'
        }
    )
    return {
        'features': [feat]
    }
Exemplo n.º 20
0
def test_FeatureCollection_valid():
    roax.geo.FeatureCollection().validate(
        geojson.FeatureCollection(
            [
                geojson.Feature(
                    geometry=geojson.Point([102.0, 0.5]), properties={"prop0": "value0"}
                ),
                geojson.Feature(
                    geometry=geojson.LineString(
                        [[102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0]]
                    ),
                    properties={"prop0": "value0", "prop1": 0.0},
                ),
                geojson.Feature(
                    geometry=geojson.Polygon(
                        [
                            [
                                [100.0, 0.0],
                                [101.0, 0.0],
                                [101.0, 1.0],
                                [100.0, 1.0],
                                [100.0, 0.0],
                            ]
                        ]
                    ),
                    properties={"prop0": "value0", "prop1": {"this": "that"}},
                ),
            ]
        )
    )
Exemplo n.º 21
0
def test_Polygon_invalid_min_rings_value():
    with pytest.raises(s.SchemaError):
        roax.geo.Polygon(min_rings=2).validate(
            geojson.Polygon(
                [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]
            )
        )
Exemplo n.º 22
0
def test_Polygon_invalid_max_rings_param():
    with pytest.raises(ValueError):
        roax.geo.Polygon(min_rings=2, max_rings=1).validate(
            geojson.Polygon(
                [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]
            )
        )
Exemplo n.º 23
0
def services(request, slug, service_category=None):
    if 'HTTP_ACCEPT_LANGUAGE' in request.META:
        accept_language = request.META['HTTP_ACCEPT_LANGUAGE'].split(',')
        first_language = accept_language[0].split('-')

        if first_language:
            first_language = first_language[0]
    else:
        first_language = 'en'

    location = models.Location.objects.filter(slug=slug)

    if location:
        location = location[0]
    else:
        return redirect('/')

    extent = geojson.Polygon(
        ([(a[0], a[1], 0) for a in location.area.shell.array], ))

    print extent

    return render(request, "service-map.html", {
        "extent": unicode(extent),
        "slug": location.slug,
    }, RequestContext(request))
Exemplo n.º 24
0
def to_geojson(best_cells, scores, explanation):
    polygons = []
    for index, cell in enumerate(best_cells):
        polygon = unite_with_nearest(cell.latitude, cell.longitude)
        polygons.append(polygon)

    count = [True] * len(polygons)

    for i in range(len(polygons) - 1):
        for j in range(len(polygons) - 1, i, -1):
            if count[i] and is_intersection(polygons[i], polygons[j]):
                count[j] = False

    if len(polygons) > 5:
        polygons = polygons[:5]

    features = []
    index = 0
    for ind, polygon in enumerate(polygons):
        if count[ind]:
            polygon = geojson.Polygon([polygon])
            feature = geojson.Feature(geometry=polygon,
                                      properties={
                                          'id': index,
                                          'score': scores[ind],
                                          'explanation': explanation[ind]
                                      })
            index += 1
            features.append(feature)

    return geojson.FeatureCollection(features)
Exemplo n.º 25
0
def convert_vissat_config_json_to_geojson(vissat_config_json_ifp, geojson_ofp):

    with open(vissat_config_json_ifp) as json_file:
        vissat_config_json = json.load(json_file)

    bbx_utm = vissat_config_json["bounding_box"]
    zone_number = bbx_utm["zone_number"]
    hemisphere = bbx_utm["hemisphere"]
    ul_easting = bbx_utm["ul_easting"]
    ul_northing = bbx_utm["ul_northing"]

    logger.info("utm: {}".format(
        ([ul_easting, ul_northing, zone_number, hemisphere])))

    # See write_aoi() in stereo_pipeline.py
    lr_easting = ul_easting + bbx_utm["width"]
    lr_northing = ul_northing - bbx_utm["height"]

    # compute a lat_lon bbx
    corners_easting = [ul_easting, lr_easting, lr_easting, ul_easting]
    corners_northing = [ul_northing, ul_northing, lr_northing, lr_northing]
    corners_lat = []
    corners_lon = []
    northern = True if hemisphere == "N" else False
    for i in range(4):
        lat, lon = utm.to_latlon(
            corners_easting[i],
            corners_northing[i],
            zone_number,
            northern=northern,
        )
        corners_lat.append(lat)
        corners_lon.append(lon)
    lat_min = min(corners_lat)
    lat_max = max(corners_lat)
    lon_min = min(corners_lon)
    lon_max = max(corners_lon)

    lat, lon = utm_to_latlon(ul_easting, ul_northing, zone_number, hemisphere)
    logger.info("lat lon: {}".format([lat, lon]))

    vertex_list = [
        (lon_min, lat_min),
        (lon_min, lat_max),
        (lon_max, lat_max),
        (lon_max, lat_min),
    ]

    # A LineString only marks the border of the area (but is not a closed
    # shape, i.e. no loop).
    # my_linestring = geojson.LineString(vertex_list)
    # geojson_str = geojson.dumps(my_linestring, sort_keys=True)

    # A polygon is filled by default in QGIS (style can be changed in the
    # raster layer properties)
    my_polygon = geojson.Polygon([vertex_list])
    geojson_str = geojson.dumps(my_polygon, sort_keys=True)

    with open(geojson_ofp, "w") as geojson_file:
        geojson_file.write(geojson_str)
Exemplo n.º 26
0
    def doSegmentation(self, image, params):
        params = self._decodeParams(params)
        self.requireParams(['seed', 'tolerance'], params)

        # validate parameters
        seedCoord = params['seed']
        if not (isinstance(seedCoord, list) and len(seedCoord) == 2
                and all(isinstance(value, int) for value in seedCoord)):
            raise ValidationException('Value must be a coordinate pair.',
                                      'seed')

        tolerance = params['tolerance']
        if not isinstance(tolerance, int):
            raise ValidationException('Value must be an integer.', 'tolerance')

        try:
            contourCoords = Segmentation().doContourSegmentation(
                image, seedCoord, tolerance)
        except GirderException as e:
            raise RestException(e.message)

        contourFeature = geojson.Feature(
            geometry=geojson.Polygon(coordinates=(contourCoords.tolist(), )),
            properties={
                'source': 'autofill',
                'seedPoint': seedCoord,
                'tolerance': tolerance
            })

        return contourFeature
Exemplo n.º 27
0
 def test_map_polygon(self):
     g = geojson.Polygon([
         [(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)], ])
     result = map_coords(lambda x: x, g)
     self.assertEqual(result['type'], 'Polygon')
     self.assertEqual(result['coordinates'][0][0], (3.78, 9.28))
     self.assertEqual(result['coordinates'][0][-1], (3.78, 9.28))
Exemplo n.º 28
0
def tryToConvertToPolygon(tags, lines, polygonize, isMultiPolygon = False):
    """
        Creates a Polygon or LineString based on the given lines
        tags: tags of the base object
        lines: coordinates (basically nested lists)
        polygonize: boolean, if True -> tries to convert every Line to Polygon
        isMultiPolygon: boolean, if each line is an extra polygon else lines = [boundary, holes..]
    """
    # as sometimes tags like "area":"no" exists, which are obviously no polygons
    tags = {tag: v for tag, v in tags.items() if not v == "no"}

    # osm-multipolygon: means just as complex area ... but geojson polygons can also handle holes
    # sometimes they are real multipolygons? (see Dresdener Heide) --> isMultiPolygon
    if POLYGON_TAGS.intersection(tags) or tags.get("type") == "multipolygon" or polygonize: 
        if isMultiPolygon:
            # creating a polygon array for each line (only exterior lines, no holes currently)
            lines = [[line] for line in lines]
            polygon = geojson.MultiPolygon(lines)
        else:
            polygon = geojson.Polygon(lines)
        if not polygon.errors():
            return polygon
        elif not polygonize:
            # with polygonize == true it is expected that this wont work every time
            logging.debug("Could not be converted to a polygon with tags {}".format(tags))
    if len(lines) == 1:
        return geojson.LineString(lines[0], validate=True)
    else:
        if LINESTRING_TAGS.intersection(tags):
            logging.debug("To many lines for a simple line for object with tags: {}".format(tags))
        return geojson.MultiLineString(lines, validate=True)
Exemplo n.º 29
0
def create_features(df):
    features = []
    properties = [
        c for c in list(df) if c not in ['name', 'geom', 'timeseries']
    ]
    for _, row in df.iterrows():
        coords = extract_coordinates(row)
        name = row['name']
        if len(coords) == 1:
            feature = gj.Feature(id=name, geometry=gj.Point(coords[0]))
        elif row['type'] == 'hub_relation':
            feature = gj.Feature(id=name, geometry=gj.Polygon([coords]))
        else:
            feature = gj.Feature(id=name, geometry=gj.LineString(coords))
        for prop in properties:
            prop_value = row[prop]
            if pd.notnull(prop_value):
                if prop == 'hubs':
                    prop_value = prop_value.split(',')
                feature['properties'][prop] = prop_value
        if 'timeseries' in df:
            ts_value = row['timeseries']
            if pd.notnull(ts_value):
                for ts in ts_value.split(','):
                    feature['properties'][ts] = list(timeseries_df[name + '.' +
                                                                   ts])
        features.append(feature)
    return features
Exemplo n.º 30
0
def random_polygon_inside_polygon(container, numverts=3):
    """
    generate a random simple polygon within the container polygon. Doesn't
    guarantee that it will be completely contained, only that the verticies
    are completely contained.
    """

    i=0
    coords = []
    mycontainer = MyPolygon(container['coordinates'][0])
    while i < numverts:
        #loop through until we have n points within the containter
        xy = (random.uniform(mycontainer.xmin, mycontainer.xmax),
              random.uniform(mycontainer.ymin, mycontainer.ymax))

        if mycontainer.contains_point(xy):
            coords.append(xy)
            i +=1
        else:
            print 'outside vert: {}'.format(xy)

    #sort points by angle about centroid
    centroid = centriod(coords)
    sortedverts = sorted(coords, key=lambda xy: angle(xy, centroid))

    #build polygon with first tuple copied at end
    return geojson.Polygon([sortedverts + [sortedverts[0]]])