Python geojson.MultiPolygon() Examples

The following are 4 code examples of geojson.MultiPolygon(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module geojson , or try the search function .
Example #1
Source File: test_geocoding.py    From ngsi-timeseries-api with MIT License 6 votes vote down vote up
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 
Example #2
Source File: multipoly.py    From geojsoncontour with MIT License 5 votes vote down vote up
def mpoly(self):
        """Output of GeoJSON MultiPolygon object."""
        return MultiPolygon(coordinates=self.coords) 
Example #3
Source File: element.py    From osm-python-tools with GNU General Public License v3.0 5 votes vote down vote up
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())) 
Example #4
Source File: api.py    From overpass-api-python-wrapper with Apache License 2.0 4 votes vote down vote up
def _as_geojson(self, elements):

        features = []
        geometry = None
        for elem in elements:
            elem_type = elem.get("type")
            elem_tags = elem.get("tags")
            elem_geom = elem.get("geometry", [])
            if elem_type == "node":
                # Create Point geometry
                geometry = geojson.Point((elem.get("lon"), elem.get("lat")))
            elif elem_type == "way":
                # Create LineString geometry
                geometry = geojson.LineString([(coords["lon"], coords["lat"]) for coords in elem_geom])
            elif elem_type == "relation":
                # Initialize polygon list
                polygons = []
                # First obtain the outer polygons
                for member in elem.get("members", []):
                    if member["role"] == "outer":
                        points = [(coords["lon"], coords["lat"]) for coords in member.get("geometry", [])]
                        # Check that the outer polygon is complete
                        if points and points[-1] == points[0]:
                            polygons.append([points])
                        else:
                            raise UnknownOverpassError("Received corrupt data from Overpass (incomplete polygon).")
                # Then get the inner polygons
                for member in elem.get("members", []):
                    if member["role"] == "inner":
                        points = [(coords["lon"], coords["lat"]) for coords in member.get("geometry", [])]
                        # Check that the inner polygon is complete
                        if points and points[-1] == points[0]:
                            # We need to check to which outer polygon the inner polygon belongs
                            point = Point(points[0])
                            check = False
                            for poly in polygons:
                                polygon = Polygon(poly[0])
                                if polygon.contains(point):
                                    poly.append(points)
                                    check = True
                                    break
                            if not check:
                                raise UnknownOverpassError("Received corrupt data from Overpass (inner polygon cannot "
                                                           "be matched to outer polygon).")
                        else:
                            raise UnknownOverpassError("Received corrupt data from Overpass (incomplete polygon).")
                # Finally create MultiPolygon geometry
                if polygons:
                    geometry = geojson.MultiPolygon(polygons)
            else:
                raise UnknownOverpassError("Received corrupt data from Overpass (invalid element).")

            if geometry:
                feature = geojson.Feature(
                    id=elem["id"],
                    geometry=geometry,
                    properties=elem_tags
                )
                features.append(feature)

        return geojson.FeatureCollection(features)