Beispiel #1
0
    def test_invalid_multipolygon(self):
        with self.assertRaises(ValueError) as cm:
            geojson.MultiPolygon([1], validate=True)

        self.assertIn("Each polygon must be a list of linear rings",
                      str(cm.exception))

        poly1 = [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
                 (25.44, -17.91)]
        poly2 = [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
                 (2.38, 57.322)]
        multipoly = geojson.MultiPolygon([poly1, poly2])
        self.assertEqual(multipoly.is_valid, False)
    def test_cant_add_task_if_not_supplied_feature_type(self):
        # Arrange
        invalid_feature = geojson.MultiPolygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38, 10.33)]])
        # Arrange

        with self.assertRaises(InvalidGeoJson):
            Task.from_geojson_feature(1, invalid_feature)
Beispiel #3
0
def to_arcgis():
    try:
        request_data = request.get_json()
        response = geojson.Feature(geometry=geojson.MultiPolygon(request_data))
        return json.dumps(response)
    except Exception as e:
        abort(400, e)
Beispiel #4
0
def _as_multipolygons(elements):
    """Parse an iterable of elements to retrieve a FeatureCollection of multipolygons.

    Parameters
    ----------
    elements : list of dict
        JSON response elements.

    Returns
    -------
    feature_collection : dict
        Output GeoJSON FeatureCollection.
    """
    features = []
    elements = [
        e for e in elements
        if e.get('type') == 'relation' and e['tags']['type'] == 'multipolygon'
    ]
    for elem in elements:
        coords = []
        for member in elem['members']:
            member_coords = []
            for node in member['geometry']:
                member_coords.append([node['lon'], node['lat']])
            coords.append(member_coords)
        geom = geojson.MultiPolygon(coordinates=[coords])
        features.append(geojson.Feature(elem['id'], geom, elem['tags']))
    return geojson.FeatureCollection(features)
Beispiel #5
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)
Beispiel #6
0
 def test_valid_multipolygon(self):
     poly1 = [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
              (2.38, 57.322)]
     poly2 = [(-5.34, 3.71), (28.74, 31.44), (28.55, 19.10), (-5.34, 3.71)]
     poly3 = [(3.14, 23.17), (51.34, 27.14), (22, -18.11), (3.14, 23.17)]
     multipoly = geojson.MultiPolygon([poly1, poly2, poly3])
     self.assertEqual(is_valid(multipoly)['valid'], YES)
Beispiel #7
0
 def test_invalid_multipolygon(self):
     poly1 = [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
              (25.44, -17.91)]
     poly2 = [(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15),
              (2.38, 57.322)]
     multipoly = geojson.MultiPolygon([poly1, poly2])
     self.assertEqual(is_valid(multipoly)['valid'], NO)
Beispiel #8
0
def es_geoshape_to_geojson(index, doc_type, geoshape_field, outfile, query={}):
    #input: ES index, doctype, and field that is mapped as a geoshape
    #output: Geojson feature collection
    es_full_url = 'http://' + ES_username + ':' + ES_password + '@' + ES_url + ':9200'
    es = Elasticsearch(es_full_url)

    features = []
    docs = helpers.scan(es,
                        index=index,
                        doc_type=doc_type,
                        query=json.dumps(query))
    for doc in docs:
        #define the geojson shape type based on ES geoshape type
        if doc['_source'][geoshape_field]['type'].lower() == 'point':
            shape = geojson.Point(
                doc['_source'][geoshape_field]['coordinates'])
        if doc['_source'][geoshape_field]['type'].lower() == 'linestring':
            shape = geojson.LineString(
                doc['_source'][geoshape_field]['coordinates'])
        if doc['_source'][geoshape_field]['type'].lower() == 'polygon':
            shape = geojson.Polygon(
                doc['_source'][geoshape_field]['coordinates'])
        if doc['_source'][geoshape_field]['type'].lower() == 'multipolygon':
            shape = geojson.MultiPolygon(
                doc['_source'][geoshape_field]['coordinates'])

        #print geojson.is_valid(shape)

        props = deepcopy(doc['_source'])
        props.pop(geoshape_field, None)
        features.append(geojson.Feature(geometry=shape, properties=props))

    with open(outfile, 'w') as out:
        geojson.dump(geojson.FeatureCollection(features), out)
Beispiel #9
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()))
Beispiel #10
0
def json2geojson(ls):
    logger = logging.getLogger('root')
    feats = []
    for dict in ls:
        #IPython.embed()
        if type(dict['properties']['ingestion_time']) == datetime.datetime:
            dttm = dict['properties']['ingestion_time']
            dttmstr = dttm.strftime("%Y-%m-%d %H:%M:%S")
            dict['properties']['ingestion_time'] = dttmstr

        if dict['geometry'] is None or len(
                dict['geometry']['coordinates']) == 0:
            feats.append(
                geojson.Feature(geometry=None, properties=dict['properties']))
        else:
            ## mixing poly and multipoly is not accepted by postgis. we will force Polygon into MultiPolygon
            mp = geojson.MultiPolygon()

            ## now we have to correct syntax of MultiPolygon which was forced from Polygon so it generates valid geojson in the end
            if dict["geometry"]["type"] == 'Polygon':
                dict["geometry"]["coordinates"] = [
                    dict["geometry"]["coordinates"]
                ]
            #if len(poly['geometry']['coordinates'])==1:
            #    mp=geojson.Polygon()

            mp['coordinates'] = dict['geometry']['coordinates']
            feats.append(
                geojson.Feature(geometry=mp, properties=dict['properties']))

    return geojson.FeatureCollection(feats)
Beispiel #11
0
 def test_multipolygon(self):
     g = geojson.MultiPolygon([
         ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],),
         ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29)],)])
     itr = coords(g)
     pairs = list(itr)
     self.assertEqual(pairs[0], (3.78, 9.28))
     self.assertEqual(pairs[-1], (23.18, -34.29))
def relation2geometry(relation):
    """
    Convert relation data into a GeoJSON object.
    """
    if check(relation, 'type', 'multipolygon'):
        outer = relation['outer']
        inner = relation['inner']
        if not inner:
            return geojson.MultiPolygon([(o['coordinates'], ) for o in outer])
        if len(outer) == 1:
            polygons = [outer[0]['coordinates']]
            for way in inner:
                polygons.append(way['coordinates'])
            return geojson.MultiPolygon([polygons])
        raise ValueError('Unknown inner/outer configuration %r' % relation)
    else:
        raise ValueError('Unknown relation type %r' % relation)
Beispiel #13
0
 def test_map_multipolygon(self):
     g = geojson.MultiPolygon([
         ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],),
         ([(23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29)],)])
     result = map_coords(lambda x: x, g)
     self.assertEqual(result['type'], 'MultiPolygon')
     self.assertEqual(result['coordinates'][0][0][0], (3.78, 9.28))
     self.assertEqual(result['coordinates'][-1][-1][-1], (23.18, -34.29))
Beispiel #14
0
 def test_invalid_multipolygon(self):
     multipolygon = geojson.MultiPolygon()
     self.assertFalse(multipolygon.is_valid())
     multipolygon.coordinates = []
     self.assertFalse(multipolygon.is_valid())
     multipolygon.coordinates = [[[[D('102.0'), D('2.0')],
                                   [D('103.0'), D('2.0')],
                                   [D('102.0'), D('3.0')]]]]
     self.assertFalse(multipolygon.is_valid())
    def test_cant_create_aoi_with_invalid_multipolygon(self):
        bad_multipolygon = geojson.MultiPolygon([[(2.38, 57.322), (23.194, -20.28), (-120.43, 19.15), (2.38)]])
        bad_feature = geojson.Feature(geometry=bad_multipolygon)
        bad_feature_collection = geojson.FeatureCollection([bad_feature])

        # Act / Assert
        with self.assertRaises(InvalidGeoJson):
            # Only geometries of type MultiPolygon are valid
            GridService.merge_to_multi_polygon(geojson.dumps(bad_feature_collection), dissolve=True)
def pd_to_geojson(df, filename, geo_col, prop_cols):
    features = []
    insert_features = lambda x: features.append(
        geojson.Feature(geometry=geojson.MultiPolygon(x[geo_col]),
                        properties=x[prop_cols].to_dict()))

    df.apply(insert_features, axis=1)
    with open('{}.geojson'.format(filename), 'w', encoding='utf8') as fp:
        geojson.dump(geojson.FeatureCollection(features), fp, sort_keys=True, ensure_ascii=False)
Beispiel #17
0
def create_feature(geometry,
                   geo_type,
                   val,
                   feature_id=None,
                   color=(255, 0, 0),
                   weight=10,
                   opacity=1.0,
                   props={}):
    """
    :param geometry: Geometry structure that creates geojson string.  Options are:
                     Point: (lng, lat) as tuple
                     MultiPoint: [Point, Point] as array of points
                     Line(string): [Point, Point, Point] as array of points
                     Multiline(string): [Line, Line] as array of lines
                     Polygon without holes: [Point1, Point, Point, Point1] as array of points,
                        first and last point in array are the same point (example makes a triangle).
                    Polygon with hole: [[Point1, Point, Point, Point1], [Point2, Point, Point, Point2]] as array of polygons,
                        second polygon is the hole.
                    Multipolygon: [Polygon, Polygon] as array of polygons (must confirm...?)
    :param geo_type: string indicating the geometry type, must match id strings from class geojson_geometry
    :param val: value to put into properties.value for mapping and style color matching
    :param feature_id: id for the geojson string
    :param color: a 3 value tuple containing an rgb value
    :param weight: for lines/polygons, line width; for points, point size
    :param opacity: opacity of layer in leaflet, 1.0 = 100%, 0 = 0%
    :returns: dictionary with geojson feature string and a leaflet style created from input parameters
    """

    try:
        if geo_type == GeojsonGeometry.point:
            geo = geojson.Point(geometry)
        elif geo_type == GeojsonGeometry.multipoint:
            geo = geojson.MultiPoint(geometry)
        elif geo_type == GeojsonGeometry.line:
            geo = geojson.LineString(geometry)
        elif geo_type == GeojsonGeometry.multiline:
            geo = geojson.MultiLineString(geometry)
        elif geo_type == GeojsonGeometry.polygon:
            geo = geojson.Polygon(geometry)
        elif geo_type == GeojsonGeometry.multipolygon:
            geo = geojson.MultiPolygon(geometry)
        else:
            print("Unsupported geometry type: " + geo_type)
            return
    except Exception as e:
        print(e, "\n probably wrong input data structure for " + geo_type)
        return

    style = None  # leaflet_style_creator()
    props['value'] = val
    geo = geojson.Feature(id=feature_id, geometry=geo, properties=props)

    ret = {'geojson': geo, 'style': style}

    return ret
Beispiel #18
0
def find_intersecting_polygons(all_polygons_file, bounding_polygon,
                               output_file, id_prefix):
    # Load all polygons into a feature set
    with open(all_polygons_file, mode="r") as in_file:
        all_polygons = geojson.load(in_file)

    total_area = 0
    num_polys = 0
    intersecting_polygons = []

    # Find the intersecting polygons
    for feature in all_polygons["features"]:
        polygon = geometry.shape(feature["geometry"])

        if not polygon.is_valid:
            if DEBUG:
                print("Attempting to fix invalid polygon")
            polygon = polygon.buffer(0)

            # If it's still not valid, just skip it
            if not polygon.is_valid:
                if DEBUG:
                    print("Fix was unsuccessful. Skipping polygon")
                continue

        intersection = bounding_polygon.intersection(polygon)

        # If polygon overlaps with bounds, we want to include it
        if intersection.area > 0:
            num_polys += 1

            # Construct new geojson polygon for intersection area
            if intersection.geom_type == 'MultiPolygon':
                new_polygon = geojson.MultiPolygon(
                    geometry.mapping(intersection)["coordinates"])
            else:
                new_polygon = geojson.Polygon(
                    geometry.mapping(intersection)["coordinates"])

            #Create feature and add to list
            new_feature = geojson.Feature(geometry=new_polygon)

            new_feature["properties"]["id"] = id_prefix + str(uuid.uuid4())

            # Add to list of features to return
            intersecting_polygons.append(new_feature)

    # Add all features to a feature set
    new_feature_collection = geojson.FeatureCollection(intersecting_polygons)

    # Output to a file
    with open(output_file, mode="w") as out_file:
        geojson.dump(new_feature_collection, out_file, indent=4)
Beispiel #19
0
def merge_pols(sceneMasks):
    mergedPolygon = shapely.geometry.Polygon()
    for fname in sceneMasks:
        with open(pths.s2aIn + '/' + fname) as geojson1:
            poly_geojson = json.load(geojson1)

            for feat in poly_geojson['features']:
                poly = shapely.geometry.asShape(feat['geometry'])
                mergedPolygon = mergedPolygon.union(poly)

    # using geojson module to convert from WKT back into GeoJSON format
    geojson_out = geojson.MultiPolygon(geometry=mergedPolygon)
    return (geojson_out)
Beispiel #20
0
def to_geojson():
    try:
        request_data = request.get_json()
        input = request_data.operationalLayers[3].featureCollection.layers[
            0].featureSet.features
        coord_set = [x["geometry"] for x in input]
        polygon_list = [Polygon(cc) for cc in coord_set]
        multipolygon = MultiPolygon(polygon_list)
        response = geojson.Feature(geometry=geojson.MultiPolygon(coord_set))
        response["bbox"] = multipolygon.bounds
        return json.dumps(response)
    except Exception as e:
        abort(400, e)
Beispiel #21
0
def aggr2geojson(polys):
    feats = []
    for poly in polys:
        oid = json.loads(json.dumps(poly['_id'], default=json_util.default))
        dttm = poly['properties']['ingestion_time']
        dttmstr = dttm.strftime("%Y-%m-%d %H:%M:%S")
        poly['properties']['ingestion_time'] = dttmstr
        del poly['_id']
        poly['properties']['oid'] = oid['$oid']

        ### rename to insert into postgis
        if 'platformname' in poly['properties']:
            poly['properties']['source_id'] = poly['properties'].pop(
                'platformname')
            if poly['properties']['source_id'] == 'Sentinel-1':
                poly['properties']['source_id'] = 1
            elif poly['properties']['source_id'] == 'Sentinel-2':
                poly['properties']['source_id'] = 2
        elif 'source_id' in poly['properties']:
            print(
                'dealing with correct geojson attributes, no need to change anything\n'
            )
        else:
            print(
                'probably one of the first scenes to be processed, before adding sentinel-2, so it must be sentinel-1! passing 1 as source_id.\n'
            )
            poly['properties']['source_id'] = 1

        if poly['geometry'] is None:
            feats.append(
                geojson.Feature(geometry=None, properties=poly['properties']))
        else:
            ## mixing poly and multiply is not accepted by postgis. we will force Polygon into MultiPolygon
            if len(poly['geometry']['coordinates']) > 0:
                mp = geojson.MultiPolygon()

            ## now we have to correct syntax of MultiPolygon which was forced from Polygon so it generates valid geojson in the end
            if poly["geometry"]["type"] == 'Polygon':
                poly["geometry"]["coordinates"] = [
                    poly["geometry"]["coordinates"]
                ]
            #if len(poly['geometry']['coordinates'])==1:
            #    mp=geojson.Polygon()

            mp['coordinates'] = poly['geometry']['coordinates']

            feats.append(
                geojson.Feature(geometry=mp, properties=poly['properties']))

    feat_col = geojson.FeatureCollection(feats)
    return (feat_col)
Beispiel #22
0
 def test_geometry_collection(self):
     geometries = geojson.GeometryCollection()
     geometries.geometries = [
         geojson.Point(coordinates=[
             random.randint(-180, 180),
             random.randint(-90, 90)
         ]) for _ in xrange(10)
     ]
     self.assertTrue(geometries.is_valid())
     multipolygon = geojson.MultiPolygon()
     multipolygon.coordinates = [[[[D('102.0'), D('2.0')],
                                   [D('103.0'), D('2.0')],
                                   [D('103.0'), D('3.0')],
                                   [D('102.0'), D('3.0')],
                                   [D('102.0'), D('2.0')]]],
                                 [[[D('100.0'), D('0.0')],
                                   [D('101.0'), D('0.0')],
                                   [D('101.0'), D('1.0')],
                                   [D('100.0'), D('1.0')],
                                   [D('100.0'), D('0.0')]],
                                  [[D('100.2'), D('0.2')],
                                   [D('100.8'), D('0.2')],
                                   [D('100.8'), D('0.8')],
                                   [D('100.2'), D('0.8')],
                                   [D('100.2'), D('0.2')]]]]
     geometries.geometries[4] = multipolygon
     multipolygon = geojson.MultiPolygon()
     multipolygon.coordinates = [[[[D('102.0'), D('2.0')],
                                   [D('103.0'), D('2.0')],
                                   [D('103.0'), D('3.0')],
                                   [D('102.0'), D('3.0')],
                                   [D('102.0'), D('2.0')]]]]
     geometries.geometries.append(multipolygon)
     self.assertTrue(geometries.is_valid())
     self.assertEquals(len(geometries), 11)
     for idx, geometry in enumerate(geometries):
         self.assertDictEquals(geometry.to_dict(),
                               geometries[idx].to_dict())
Beispiel #23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--image",
                        type=str,
                        default="GoogleSatellite-x215782-y99255-z18.jpg",
                        help="the base map image")
    parser.add_argument(
        "--bounds",
        type=str,
        default=
        "[[39.98553841480973, 116.33148193359375], [39.98659063142852, 116.33285522460938]]",
        help="the latitude-longitude bounds of the base map image")
    parser.add_argument("--input",
                        type=str,
                        default="input.txt",
                        help="the input file")
    parser.add_argument("--output",
                        type=str,
                        default="output.json",
                        help="the output file")
    parser.add_argument(
        "--input-is-percent",
        action="store_true",
        help="whether the input coordinate is percent (or int)")
    args = parser.parse_args()

    image_ = image.imread(args.image)
    image_height, image_width = image_.shape[0], image_.shape[1]
    bounds = json.loads(args.bounds)
    lat_min, lon_min, lat_max, lon_max, lat_span, lon_span = bounds[0][
        0], bounds[0][1], bounds[1][0], bounds[1][1], (
            bounds[1][0] - bounds[0][0]), (bounds[1][1] - bounds[0][1])
    input_lines = open(args.input).readlines(
    )  # image coordinate system origin: top left corner, coordinate order: x,y

    feature_collection = geojson.FeatureCollection([
        geojson.Feature(id=str(i),
                        geometry=geojson.MultiPolygon(json.loads(line)))
        for i, line in enumerate(input_lines)
    ])
    if args.input_is_percent:
        feature_collection = geojson.utils.map_tuples(
            lambda c: (lon_min + lon_span * c[0], lat_min + lat_span *
                       (1.0 - c[1])), feature_collection)
    else:
        feature_collection = geojson.utils.map_tuples(
            lambda c:
            (lon_min + lon_span * (c[0] / image_width), lat_min + lat_span *
             (1.0 - c[1] / image_height)), feature_collection)
    open(args.output, "wt").write(geojson.dumps(feature_collection, indent=2))
def validate_multi_polygon(multipolygon_coordinates: List[List[List[float]]]):
    """according: https://en.wikipedia.org/wiki/GeoJSON"""
    multipolygon = geojson.MultiPolygon(multipolygon_coordinates)

    if not multipolygon.is_valid:
        raise ValueError('MultiPolygon is not valid')

    for level_01 in multipolygon.coordinates:
        for level_02 in level_01:
            for level_03 in level_02:
                latitude_valid = validate_latitude(level_03[0])
                longitude_valid = validate_longitude(level_03[1])
                if not latitude_valid or not longitude_valid:
                    raise ValueError('coordinates is not valid')
Beispiel #25
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)
Beispiel #26
0
def l2geojson(l, type='Polygon'):

    features_l = []
    for ll in l:
        if type == 'Polygon':
            p = geojson.Polygon(ll)
        elif type == 'Point':
            p = geojson.Point(ll)
        else:
            p = geojson.MultiPolygon(ll)

        f = geojson.Feature(geometry=p)
        features_l.append(f)

    geodata = geojson.dumps(geojson.FeatureCollection(features=features_l))
    return geodata
Beispiel #27
0
    def test_nested_constructors(self):
        a = [5, 6]
        b = [9, 10]
        c = [-5, 12]
        mp = geojson.MultiPoint([geojson.Point(a), b])
        self.assertEqual(mp.coordinates, [a, b])

        mls = geojson.MultiLineString([geojson.LineString([a, b]), [a, c]])
        self.assertEqual(mls.coordinates, [[a, b], [a, c]])

        outer = [a, b, c, a]
        poly = geojson.Polygon(geojson.MultiPoint(outer))
        other = [[1, 1], [1, 2], [2, 1], [1, 1]]
        poly2 = geojson.Polygon([outer, other])
        self.assertEqual(geojson.MultiPolygon([poly, poly2]).coordinates,
                         [[outer], [outer, other]])
Beispiel #28
0
def build_features(shp, dbf):
    '''
    Builds a GeoJSON object from a PySAL shapefile and DBF object

    shp - shapefile opened using pysal.open(file)
    dbf - dbase table opened using pysal.open(file)

    Only polygonal lattices are supported. 
    '''

    shp_bak = ps.open(shp.dataPath)
    dbf_bak = ps.open(dbf.dataPath)

    chains = shp_bak.read()
    dbftable = dbf_bak.read()

    shp_bak.close()
    dbf_bak.close()

    #shptype = str(shp_bak.type).strip("<class 'pysal.cg.shapes.").strip("'>")

    if 'Polygon' in str(shp_bak.type):
        ftype = 'Polygon'
    elif 'Point' in str(type(shp_bak.type)):
        raise NotImplementedError('Point data is not implemented yet')

    if ftype == "Polygon":
        feats = []
        for idx in range(len(chains)):
            chain = chains[idx]
            if len(chain.parts) > 1:
                #shptype = 'MultiPolygon'
                geom = gj.MultiPolygon([[[list(coord) for coord in part]]
                                        for part in chain.parts])
            else:
                #shptype = 'Polygon'
                geom = gj.Polygon(coordinates=[[list(coord) for coord in part]
                                               for part in chain.parts])
            prop = {
                head: val
                for head, val in zip(dbf_bak.header, dbftable[idx])
            }
            bbox = chain.bbox
            feats.append(
                gj.Feature(None, geometry=geom, properties=prop, bbox=bbox))

    return gj.FeatureCollection(feats, bbox=shp_bak.bbox)
def test_entity_add_country_shape(air_quality_observed):
    air_quality_observed.pop('location')

    air_quality_observed['address']['value'] = {
        "addressCountry": "MX",
    }

    r = geocoding.add_location(air_quality_observed)
    assert r is air_quality_observed

    assert 'location' in r
    assert r['location']['type'] == 'geo:json'

    geo = r['location']['value']
    assert geo['type'] == 'MultiPolygon'
    multi_polygon = geojson.MultiPolygon(geo['coordinates'])
    assert multi_polygon.is_valid
Beispiel #30
0
 def test_geometrycollection(self):
     p1 = geojson.Point((-115.11, 37.11))
     p2 = geojson.Point((-115.22, 37.22))
     ln = geojson.LineString(
         [(-115.3, 37.3), (-115.4, 37.4), (-115.5, 37.5)])
     g = geojson.MultiPolygon([
         ([(3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28)],),
         ([(23.18, -34.29), (-1.31, -4.61),
           (3.41, 77.91), (23.18, -34.29)],)])
     itr = coords(geojson.GeometryCollection([p1, p2, ln, g]))
     pairs = set(itr)
     self.assertEqual(pairs, set([
         (-115.11, 37.11), (-115.22, 37.22),
         (-115.3, 37.3), (-115.4, 37.4), (-115.5, 37.5),
         (3.78, 9.28), (-130.91, 1.52), (35.12, 72.234), (3.78, 9.28),
         (23.18, -34.29), (-1.31, -4.61), (3.41, 77.91), (23.18, -34.29)
     ]))