Example #1
0
    def to_python(self, value):
        """Transform the value to a Geometry object."""
        if value in self.empty_values:
            return None

        if not isinstance(value, GEOSGeometry):
            if hasattr(self.widget, 'deserialize'):
                try:
                    value = self.widget.deserialize(value)
                except GDALException:
                    value = None
            else:
                try:
                    value = GEOSGeometry(value)
                except (GEOSException, ValueError, TypeError):
                    value = None
            if value is None:
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
Example #2
0
    def to_python(self, value):
        """Transform the value to a Geometry object."""
        if value in self.empty_values:
            return None

        if not isinstance(value, GEOSGeometry):
            if hasattr(self.widget, 'deserialize'):
                try:
                    value = self.widget.deserialize(value)
                except GDALException:
                    value = None
            else:
                try:
                    value = GEOSGeometry(value)
                except (GEOSException, ValueError, TypeError):
                    value = None
            if value is None:
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
Example #3
0
    def from_native(self, value):
        import json
        geom = GEOSGeometry(json.dumps(value))
        srid = getattr(settings, 'SRID', 4326)

        if 'crs' in value and value['crs'].get('type', None) == 'name':
            name = value['crs']['properties']['name']
            if name.startswith('urn:ogc:def:crs:EPSG::'):
                geom.srid = int(name.replace('urn:ogc:def:crs:EPSG::', ''))

        if geom.srid is None:
            geom.srid = 4326
        if geom.srid != srid:
            geom.transform(srid)
        return geom
Example #4
0
def tile_json(request, layer_name, z, x, y):
    x, y, z = int(x), int(y), int(z)
    # mimetype, data = stache(request, layer_name, z, x, y, "mvt")
    # mvt_features = mvt.decode(StringIO(data))

    if request.tenant is not None:
        cache_path = os.path.join(settings.STATIC_ROOT, "tiles",
                                  "tenant-" + str(request.tenant.pk))
    else:
        cache_path = os.path.join(settings.STATIC_ROOT, "tiles")

    mvt_features = manual_mvt(cache_path, layer_name, z, x, y)
    features = []
    for wkb, props in mvt_features:
        geom = GEOSGeometry(buffer(wkb))
        geom.srid = 3857
        geom.transform(4326)

        try:
            props['properties']['id'] = props['__id__']
        except Exception as e:
            print('tile_json', e)

        feature = '{ "type": "Feature", "geometry": ' + geom.json + ","
        feature += ' "properties": {}'.format(json.dumps(props['properties']))
        feature += '}'
        features.append(feature)

    features = ",\n".join(features)
    response = '{"type": "FeatureCollection", "features": [' + features + ']}'
    return HttpResponse(response, content_type="application/json")
Example #5
0
def processa(p1, p2):

    cidade = get_ibge(p1, p2)

    str_ponto = 'POINT({0} {1})'.format(p2, p1)
    pt = GEOSGeometry(str_ponto)
    pt.srid = 4326

    normal = automatica_proxima(pt, 'N')
    automatica = automatica_proxima(pt, 'A')

    result = {
        'normal': {
            'estacao': normal.Nome,
            'dist': str(round(normal.distance.km, 2)),
            'id': str(normal.id)
        },
        'automatica': {
            'estacao': automatica.Nome,
            'dist': str(round(automatica.distance.km, 2)),
            'id': str(automatica.id),
            'codigo': automatica.Codigo
        },
        'cidade': cidade,
    }
    return result
Example #6
0
    def get_prep_value(self, value):
        obj = super().get_prep_value(value)
        if obj is None:
            return None
        # When the input is not a geometry or raster, attempt to construct one
        # from the given string input.
        if isinstance(obj, GEOSGeometry):
            pass
        else:
            # Check if input is a candidate for conversion to raster or geometry.
            is_candidate = isinstance(obj, (bytes, str)) or hasattr(
                obj, '__geo_interface__')
            # Try to convert the input to raster.
            raster = self.get_raster_prep_value(obj, is_candidate)

            if raster:
                obj = raster
            elif is_candidate:
                try:
                    obj = GEOSGeometry(obj)
                except (GEOSException, GDALException):
                    raise ValueError(
                        "Couldn't create spatial object from lookup value '%s'."
                        % obj)
            else:
                raise ValueError(
                    'Cannot use object with type %s for a spatial lookup parameter.'
                    % type(obj).__name__)

        # Assigning the SRID value.
        obj.srid = self.get_srid(obj)
        return obj
Example #7
0
    def get_prep_value(self, value):
        obj = super().get_prep_value(value)
        # When the input is not a geometry or raster, attempt to construct one
        # from the given string input.
        if isinstance(obj, GEOSGeometry):
            pass
        else:
            # Check if input is a candidate for conversion to raster or geometry.
            is_candidate = isinstance(obj, (bytes, str)) or hasattr(obj, '__geo_interface__')
            # Try to convert the input to raster.
            raster = self.get_raster_prep_value(obj, is_candidate)

            if raster:
                obj = raster
            elif is_candidate:
                try:
                    obj = GEOSGeometry(obj)
                except (GEOSException, GDALException):
                    raise ValueError("Couldn't create spatial object from lookup value '%s'." % obj)
            else:
                raise ValueError('Cannot use object with type %s for a spatial lookup parameter.' % type(obj).__name__)

        # Assigning the SRID value.
        obj.srid = self.get_srid(obj)
        return obj
Example #8
0
    def to_internal_value(self, value):
        import json
        if isinstance(value, dict):
            value = json.dumps(value)
        geom = GEOSGeometry(value)
        srid = getattr(settings, 'SRID', 4326)

        if 'crs' in value and value['crs'].get('type', None) == 'name':
            name = value['crs']['properties']['name']
            if name.startswith('urn:ogc:def:crs:EPSG::'):
                geom.srid = int(name.replace('urn:ogc:def:crs:EPSG::', ''))

        if geom.srid is None:
            geom.srid = 4326
        if geom.srid != srid:
            geom.transform(srid)
        return geom
    def get_polygons(self, geom):
        result = GEOSGeometry(json.dumps(geom))

        if isinstance(result, Polygon):
            result = MultiPolygon(result)

        if self.srid:
            result.srid = self.srid

        return result
Example #10
0
 def form_valid(self, form):
     lat = form.cleaned_data.get('lat')
     lng = form.cleaned_data.get('lng')
     wkt = "POINT({} {})".format(lng, lat)
     point = GEOSGeometry(wkt)
     point.srid = 4326
     form.instance.geom = point
     form.save()
     messages.success(self.request, 'Your point was  updated successfully!')
     return super().form_valid(form)
Example #11
0
    def test04_wkbwriter(self):
        wkb_w = WKBWriter()

        # Representations of 'POINT (5 23)' in hex -- one normal and
        # the other with the byte order changed.
        g = GEOSGeometry("POINT (5 23)")
        hex1 = b"010100000000000000000014400000000000003740"
        wkb1 = memoryview(binascii.a2b_hex(hex1))
        hex2 = b"000000000140140000000000004037000000000000"
        wkb2 = memoryview(binascii.a2b_hex(hex2))

        self.assertEqual(hex1, wkb_w.write_hex(g))
        self.assertEqual(wkb1, wkb_w.write(g))

        # Ensuring bad byteorders are not accepted.
        for bad_byteorder in (-1, 2, 523, "foo", None):
            # Equivalent of `wkb_w.byteorder = bad_byteorder`
            with self.assertRaises(ValueError):
                wkb_w._set_byteorder(bad_byteorder)

        # Setting the byteorder to 0 (for Big Endian)
        wkb_w.byteorder = 0
        self.assertEqual(hex2, wkb_w.write_hex(g))
        self.assertEqual(wkb2, wkb_w.write(g))

        # Back to Little Endian
        wkb_w.byteorder = 1

        # Now, trying out the 3D and SRID flags.
        g = GEOSGeometry("POINT (5 23 17)")
        g.srid = 4326

        hex3d = b"0101000080000000000000144000000000000037400000000000003140"
        wkb3d = memoryview(binascii.a2b_hex(hex3d))
        hex3d_srid = (
            b"01010000A0E6100000000000000000144000000000000037400000000000003140"
        )
        wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))

        # Ensuring bad output dimensions are not accepted
        for bad_outdim in (-1, 0, 1, 4, 423, "foo", None):
            with self.assertRaisesMessage(
                    ValueError, "WKB output dimension must be 2 or 3"):
                wkb_w.outdim = bad_outdim

        # Now setting the output dimensions to be 3
        wkb_w.outdim = 3

        self.assertEqual(hex3d, wkb_w.write_hex(g))
        self.assertEqual(wkb3d, wkb_w.write(g))

        # Telling the WKBWriter to include the srid in the representation.
        wkb_w.srid = True
        self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
        self.assertEqual(wkb3d_srid, wkb_w.write(g))
Example #12
0
    def test04_wkbwriter(self):
        wkb_w = WKBWriter()

        # Representations of 'POINT (5 23)' in hex -- one normal and
        # the other with the byte order changed.
        g = GEOSGeometry('POINT (5 23)')
        hex1 = b'010100000000000000000014400000000000003740'
        wkb1 = memoryview(binascii.a2b_hex(hex1))
        hex2 = b'000000000140140000000000004037000000000000'
        wkb2 = memoryview(binascii.a2b_hex(hex2))

        self.assertEqual(hex1, wkb_w.write_hex(g))
        self.assertEqual(wkb1, wkb_w.write(g))

        # Ensuring bad byteorders are not accepted.
        for bad_byteorder in (-1, 2, 523, 'foo', None):
            # Equivalent of `wkb_w.byteorder = bad_byteorder`
            self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)

        # Setting the byteorder to 0 (for Big Endian)
        wkb_w.byteorder = 0
        self.assertEqual(hex2, wkb_w.write_hex(g))
        self.assertEqual(wkb2, wkb_w.write(g))

        # Back to Little Endian
        wkb_w.byteorder = 1

        # Now, trying out the 3D and SRID flags.
        g = GEOSGeometry('POINT (5 23 17)')
        g.srid = 4326

        hex3d = b'0101000080000000000000144000000000000037400000000000003140'
        wkb3d = memoryview(binascii.a2b_hex(hex3d))
        hex3d_srid = b'01010000A0E6100000000000000000144000000000000037400000000000003140'
        wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))

        # Ensuring bad output dimensions are not accepted
        for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
            # Equivalent of `wkb_w.outdim = bad_outdim`
            self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)

        # These tests will fail on 3.0.0 because of a bug that was fixed in 3.1:
        # http://trac.osgeo.org/geos/ticket/216
        if not geos_version_info()['version'].startswith('3.0.'):
            # Now setting the output dimensions to be 3
            wkb_w.outdim = 3

            self.assertEqual(hex3d, wkb_w.write_hex(g))
            self.assertEqual(wkb3d, wkb_w.write(g))

            # Telling the WKBWriter to include the srid in the representation.
            wkb_w.srid = True
            self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
            self.assertEqual(wkb3d_srid, wkb_w.write(g))
Example #13
0
    def test04_wkbwriter(self):
        wkb_w = WKBWriter()

        # Representations of 'POINT (5 23)' in hex -- one normal and
        # the other with the byte order changed.
        g = GEOSGeometry('POINT (5 23)')
        hex1 = '010100000000000000000014400000000000003740'
        wkb1 = buffer(binascii.a2b_hex(hex1))
        hex2 = '000000000140140000000000004037000000000000'
        wkb2 = buffer(binascii.a2b_hex(hex2))

        self.assertEqual(hex1, wkb_w.write_hex(g))
        self.assertEqual(wkb1, wkb_w.write(g))

        # Ensuring bad byteorders are not accepted.
        for bad_byteorder in (-1, 2, 523, 'foo', None):
            # Equivalent of `wkb_w.byteorder = bad_byteorder`
            self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)
            
        # Setting the byteorder to 0 (for Big Endian)
        wkb_w.byteorder = 0
        self.assertEqual(hex2, wkb_w.write_hex(g))
        self.assertEqual(wkb2, wkb_w.write(g))

        # Back to Little Endian
        wkb_w.byteorder = 1

        # Now, trying out the 3D and SRID flags.
        g = GEOSGeometry('POINT (5 23 17)')
        g.srid = 4326
        
        hex3d = '0101000080000000000000144000000000000037400000000000003140'
        wkb3d = buffer(binascii.a2b_hex(hex3d))
        hex3d_srid = '01010000A0E6100000000000000000144000000000000037400000000000003140'
        wkb3d_srid = buffer(binascii.a2b_hex(hex3d_srid))

        # Ensuring bad output dimensions are not accepted
        for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
            # Equivalent of `wkb_w.outdim = bad_outdim`
            self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)

        # These tests will fail on 3.0.0 because of a bug that was fixed in 3.1:
        # http://trac.osgeo.org/geos/ticket/216
        if not geos_version_info()['version'].startswith('3.0.'):
            # Now setting the output dimensions to be 3
            wkb_w.outdim = 3

            self.assertEqual(hex3d, wkb_w.write_hex(g))
            self.assertEqual(wkb3d, wkb_w.write(g))

            # Telling the WKBWriter to inlcude the srid in the representation.
            wkb_w.srid = True
            self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
            self.assertEqual(wkb3d_srid, wkb_w.write(g))
    def to_python(self, value):
        """
        Transforms the value to a Geometry object.
        """
        if value in validators.EMPTY_VALUES:
            return None

        if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
Example #15
0
    def to_internal_value(self, value):
        import json
        if isinstance(value, dict):
            value = json.dumps(value)

        if not GEOSGeometry:
            raise Exception("Missing GDAL")

        geom = GEOSGeometry(value)
        srid = getattr(settings, 'SRID', 4326)

        if 'crs' in value and value['crs'].get('type', None) == 'name':
            name = value['crs']['properties']['name']
            if name.startswith('urn:ogc:def:crs:EPSG::'):
                geom.srid = int(name.replace('urn:ogc:def:crs:EPSG::', ''))

        if geom.srid is None:
            geom.srid = 4326
        if geom.srid != srid:
            geom.transform(srid)
        return geom
Example #16
0
    def test04_wkbwriter(self):
        wkb_w = WKBWriter()

        # Representations of 'POINT (5 23)' in hex -- one normal and
        # the other with the byte order changed.
        g = GEOSGeometry('POINT (5 23)')
        hex1 = b'010100000000000000000014400000000000003740'
        wkb1 = memoryview(binascii.a2b_hex(hex1))
        hex2 = b'000000000140140000000000004037000000000000'
        wkb2 = memoryview(binascii.a2b_hex(hex2))

        self.assertEqual(hex1, wkb_w.write_hex(g))
        self.assertEqual(wkb1, wkb_w.write(g))

        # Ensuring bad byteorders are not accepted.
        for bad_byteorder in (-1, 2, 523, 'foo', None):
            # Equivalent of `wkb_w.byteorder = bad_byteorder`
            with self.assertRaises(ValueError):
                wkb_w._set_byteorder(bad_byteorder)

        # Setting the byteorder to 0 (for Big Endian)
        wkb_w.byteorder = 0
        self.assertEqual(hex2, wkb_w.write_hex(g))
        self.assertEqual(wkb2, wkb_w.write(g))

        # Back to Little Endian
        wkb_w.byteorder = 1

        # Now, trying out the 3D and SRID flags.
        g = GEOSGeometry('POINT (5 23 17)')
        g.srid = 4326

        hex3d = b'0101000080000000000000144000000000000037400000000000003140'
        wkb3d = memoryview(binascii.a2b_hex(hex3d))
        hex3d_srid = b'01010000A0E6100000000000000000144000000000000037400000000000003140'
        wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))

        # Ensuring bad output dimensions are not accepted
        for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
            # Equivalent of `wkb_w.outdim = bad_outdim`
            with self.assertRaises(ValueError):
                wkb_w._set_outdim(bad_outdim)

        # Now setting the output dimensions to be 3
        wkb_w.outdim = 3

        self.assertEqual(hex3d, wkb_w.write_hex(g))
        self.assertEqual(wkb3d, wkb_w.write(g))

        # Telling the WKBWriter to include the srid in the representation.
        wkb_w.srid = True
        self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
        self.assertEqual(wkb3d_srid, wkb_w.write(g))
    def to_python(self, value):
        """
        Transforms the value to a Geometry object.
        """
        if value in validators.EMPTY_VALUES:
            return None

        if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')

        # Try to set the srid
        if not value.srid:
            try:
                value.srid = self.widget.map_srid
            except AttributeError:
                if self.srid:
                    value.srid = self.srid
        return value
def normalize_geo(point):
    """
    If we encounter a polygon. change it to point
    """

    if point['type'] == 'Point':
        n_point = GEOSGeometry(json.dumps(point))
    elif point['type'] == 'Polygon':
        # create centroid from polygon (ligplaats)
        n_point = GEOSGeometry(json.dumps(point)).centroid

    # geojson now defaults to 4326!
    n_point.srid = 28992
    return n_point
def normalize_geo(point):
    """
    If we encounter a polygon. change it to point
    """

    if point['type'] == 'Point':
        n_point = GEOSGeometry(json.dumps(point))
    elif point['type'] == 'Polygon':
        # create centroid from polygon (ligplaats)
        n_point = GEOSGeometry(json.dumps(point)).centroid

    # geojson now defaults to 4326!
    n_point.srid = 28992
    return n_point
Example #20
0
    def to_python(self, value):
        """
        Transforms the value to a Geometry object.
        """
        if value in self.empty_values:
            return None

        if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
                if not value.srid:
                    value.srid = self.widget.map_srid
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
        return value
Example #21
0
    def to_python(self, value):
        """
        Transforms the value to a Geometry object.
        """
        if value in self.empty_values:
            return None

        if not isinstance(value, GEOSGeometry):
            try:
                value = GEOSGeometry(value)
                if not value.srid:
                    value.srid = self.widget.map_srid
            except (GEOSException, ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
        return value
    def _convert_point(self):
        '''
         Get the point lat , lng
         Convert the point in Point object
        '''

        lng = self.data[0]
        lat = self.data[1]
        wkt = "POINT({} {})".format(lng, lat)
        print(wkt)
        try:
            point = GEOSGeometry(wkt)
            point.srid = 4326
        except GEOSException:
            point = None
        return point
Example #23
0
    def handle_wkt(self, wkt, name):
        g1 = GEOSGeometry(wkt)
        srid = g1.srid
        if not srid:
            raise Exception("Unknown SRID. Try ewkt format; `SRID=4326;POLYGON((.....))`")
        if g1 and isinstance(g1, geos.Polygon):
            g1 = geos.MultiPolygon(g1)
            g1.srid = srid

        if not name:
            raise Exception("No --name provided!")

        g1.transform(settings.GEOMETRY_DB_SRID)
        region = StudyRegion.objects.create(geometry=g1, name=name, active=True)
        region.save()

        print "Study region created: %s, primary key = %s" % (region.name, region.pk)
Example #24
0
def dynamic_geojson(request):
    bbox = request.GET.get('bbox', None)
    if bbox:
        bbox = [float(x) for x in bbox.split(',')]
    else:
        bbox = [-180, -90, 180, 90]  # TODO: calc to 3857
    bbox_dict = {
        'min_x': bbox[0],
        'min_y': bbox[1],
        'max_x': bbox[2],
        'max_y': bbox[3],
    }
    geom = GEOSGeometry(
        'POLYGON (({min_x} {min_y}, {min_x} {max_y}, {max_x} {max_y}, {max_x} {min_y}, {min_x} {min_y}))'
        .format(**bbox_dict))
    geom.srid = 3857
    geom.transform(TRANSF)
    points = Points.objects.filter(geom_point__bboverlaps=geom)
    return HttpResponse(serialize('geojson', points),
                        content_type='application/json')
Example #25
0
def dynamic_geojson(request):
    bbox = request.GET.get('bbox', None)
    if bbox:
        bbox = [float(x) for x in bbox.split(',')]
    else:
        bbox = [-180, -90, 180, 90]  # TODO: calc to 3857
    bbox_dict = {
        'min_x': bbox[0],
        'min_y': bbox[1],
        'max_x': bbox[2],
        'max_y': bbox[3],
        }
    geom = GEOSGeometry(
        'POLYGON (({min_x} {min_y}, {min_x} {max_y}, {max_x} {max_y}, {max_x} {min_y}, {min_x} {min_y}))'.format(
            **bbox_dict
        ))
    geom.srid = 3857
    geom.transform(TRANSF)
    points = Points.objects.filter(geom_point__bboverlaps=geom)
    return HttpResponse(serialize('geojson', points), content_type='application/json')
Example #26
0
    def handle_wkt(self, wkt, name):
        g1 = GEOSGeometry(wkt)
        srid = g1.srid
        if not srid:
            raise Exception(
                "Unknown SRID. Try ewkt format; `SRID=4326;POLYGON((.....))`")
        if g1 and isinstance(g1, geos.Polygon):
            g1 = geos.MultiPolygon(g1)
            g1.srid = srid

        if not name:
            raise Exception("No --name provided!")

        g1.transform(settings.GEOMETRY_DB_SRID)
        region = StudyRegion.objects.create(geometry=g1,
                                            name=name,
                                            active=True)
        region.save()

        print "Study region created: %s, primary key = %s" % (region.name,
                                                              region.pk)
Example #27
0
    def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        if not value:
            if self.null and not self.required:
                # The geometry column allows NULL and is not required.
                return None
            else:
                raise forms.ValidationError(self.error_messages['no_geom'])

        # Trying to create a Geometry object from the form value.
        try:
            geom = GEOSGeometry(value)
        except:
            raise forms.ValidationError(self.error_messages['invalid_geom'])

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper(
        ) != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(
                self.error_messages['invalid_geom_type'])

        # Transforming the geometry if the SRID was set.
        if self.srid:
            if not geom.srid:
                # Should match that of the field if not given.
                geom.srid = self.srid
            elif self.srid != -1 and self.srid != geom.srid:
                try:
                    geom.transform(self.srid)
                except:
                    raise forms.ValidationError(
                        self.error_messages['transform_error'])

        return geom
Example #28
0
def add(request):
    """ Add new project """

    # save form
    if request.method == 'POST':
        new_project = Project()
        project = ProjectForm(request.POST, instance=new_project)
        # TODO: mixin permission check
        if project.is_valid():
            # transform location
            entry = project.save(commit=False)
            new_location = GEOSGeometry(entry.location)
            new_location.srid = 4326
            new_location.transform(26986)
            entry.location = new_location
            entry.save( user=request.user, update_walkscore=True )
            return redirect('detail', dd_id=entry.dd_id)
    # show empty form
    else:
        project = ProjectForm()

    return render_to_response('development/update.html', locals(), context_instance=RequestContext(request))
    def _convert_linestring(self):
        '''
         Get the route from the  array
         Convert the route in LineString object
        '''

        linestring_raw = ''
        k = 0
        for i in self.data:
            k += 1
            if i in linestring_raw:
                pass
            else:
                linestring_raw += i
                linestring_raw += ','
        wkt = "LineString({})".format(linestring_raw).replace(',)', ')')
        try:
            linestring = GEOSGeometry(wkt)
            linestring.srid = 4326
        except GEOSException:
            linestring = None
        return linestring
    def _convert_polygon(self):
        '''
         Get the polygon from the  array
         Convert the polygon in Polygon object
        '''

        polygon_raw_string = ''
        for i in self.data:
            if i in polygon_raw_string:
                pass
            else:
                polygon_raw_string += i
                polygon_raw_string += ' , '

        polygon_raw_string += self.data[0]
        wkt = "POLYGON((" + polygon_raw_string + "))"
        try:
            polygon = GEOSGeometry(wkt)
            polygon.srid = 4326
        except GEOSException:
            polygon = None
        return polygon
Example #31
0
def processa(p1,p2):

    cidade = get_ibge(p1, p2)

    str_ponto = 'POINT({0} {1})'.format(p2,p1)
    pt = GEOSGeometry(str_ponto)
    pt.srid = 4326

    normal = automatica_proxima(pt, 'N')
    automatica = automatica_proxima(pt, 'A')

    result = { 'normal' : { 'estacao' : normal.Nome,
                            'dist' : str(round(normal.distance.km,2)),
                            'id' : str(normal.id)
                          } ,
               'automatica' : { 'estacao' : automatica.Nome,
                                'dist' : str(round(automatica.distance.km,2)),
                                'id' : str(automatica.id),
                                'codigo' : automatica.Codigo
                               },
               'cidade' : cidade,
            }
    return result
Example #32
0
def add(request):
    """ Add new project """

    # save form
    if request.method == 'POST':
        new_project = Project()
        project = ProjectForm(request.POST, instance=new_project)
        # TODO: mixin permission check
        if project.is_valid():
            # transform location
            entry = project.save(commit=False)
            new_location = GEOSGeometry(entry.location)
            new_location.srid = 4326
            new_location.transform(26986)
            entry.location = new_location
            entry.save(user=request.user, update_walkscore=True)
            return redirect('detail', dd_id=entry.dd_id)
    # show empty form
    else:
        project = ProjectForm()

    return render_to_response('development/update.html',
                              locals(),
                              context_instance=RequestContext(request))
    def to_internal_value(self, data):
        """
        Accepts string or dict representation
        of a geojson polygon or multipolygon,
        either contained in a feature or standalone.

        Validates the shape can be processed, and
        returns a MultiPolygon geojson string.
        """
        if data == '' or data is None:
            return data
        if isinstance(data, str):
            data = json.loads(data)

        geometry = data

        try:
            if not isinstance(geometry, GEOSGeometry):
                geometry = data['geometry'] if 'geometry' in data else data
                geometry = GEOSGeometry(json.dumps(geometry))
            geometry.srid = 4326
        except Exception:
            raise ValidationError('Area of interest must ' +
                                  'be valid GeoJSON, of type ' +
                                  'Feature, Polygon or MultiPolygon')

        if geometry.dims != 2:
            raise ValidationError('Area of interest must be a Polygon' +
                                  ' or MultiPolygon')

        if geometry.geom_type == 'Polygon':
            geometry = MultiPolygon(geometry, srid=4326)

        validate_aoi(geometry)

        return geometry.geojson
Example #34
0
    def clean(self, value):
        """
        Validates that the input value can be converted to a Geometry
        object (which is returned).  A ValidationError is raised if
        the value cannot be instantiated as a Geometry.
        """
        if not value:
            if self.null and not self.required:
                # The geometry column allows NULL and is not required.
                return None
            else:
                raise forms.ValidationError(self.error_messages['no_geom'])

        # Trying to create a Geometry object from the form value.
        try:
            geom = GEOSGeometry(value)
        except:
            raise forms.ValidationError(self.error_messages['invalid_geom'])

        # Ensuring that the geometry is of the correct type (indicated
        # using the OGC string label).
        if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
            raise forms.ValidationError(self.error_messages['invalid_geom_type'])

        # Transforming the geometry if the SRID was set.
        if self.srid:
            if not geom.srid:
                # Should match that of the field if not given.
                geom.srid = self.srid
            elif self.srid != -1 and self.srid != geom.srid:
                try:
                    geom.transform(self.srid)
                except:
                    raise forms.ValidationError(self.error_messages['transform_error'])

        return geom
Example #35
0
def update(request, dd_id):
    """ Update existing project """

    try:
        project = Project.objects.transform(4326).get(pk=dd_id)
    except Project.DoesNotExist:
        raise Http404

    # TODO: refactor this whole block

    if has_permissions(request.user, project.taz.municipality):

        user = request.user.profile

        if request.method == 'POST':
            mod_proj = ModeratedProject.new_from_project(project)
            mod_proj.user = request.user

            updated_project = ModeratedProjectForm(request.POST,
                                                   instance=mod_proj)

            if updated_project.is_valid():
                entry = updated_project.save(commit=False)
                new_location = GEOSGeometry(entry.location)
                new_location.srid = 4326
                new_location.transform(26986)

                entry.location = new_location

                entry.save(user=request.user, update_walkscore=True)

                if user.is_trusted() or user.is_municipal():
                    # TODO: refactor
                    entry.accept()
                    municipal_users = User.objects.filter(
                        profile__municipality=entry.municipality())
                    emails = [user.email for user in municipal_users]

                    body = get_template(
                        'mail_templates/new_published_edit.html').render(
                            Context({
                                'project_id': entry.project.dd_id,
                                'project_name': entry.project.ddname,
                                'municipality_name': entry.municipality().name,
                                'project': entry,
                                'domain': request.META['HTTP_HOST'],
                            }))

                    send_mail('Development Database: New Published Edit',
                              body,
                              emails.pop(),
                              emails,
                              fail_silently=False)

                    messages.add_message(
                        request, messages.INFO,
                        'You are a trusted user, so your edits will be published immediately.'
                    )
                else:
                    # TODO: refactor
                    municipal_users = User.objects.filter(
                        profile__municipality=entry.municipality())
                    emails = [user.email for user in municipal_users]

                    body = get_template(
                        'mail_templates/new_pending_edit.html').render(
                            Context({
                                'project_id': entry.project.dd_id,
                                'project_name': entry.project.ddname,
                                'municipality_name': entry.municipality().name,
                                'project': entry,
                                'domain': request.META['HTTP_HOST'],
                            }))

                    send_mail('Development Database: New Pending Edit',
                              body,
                              emails.pop(),
                              emails,
                              fail_silently=False)

                    messages.add_message(request, messages.INFO,
                                         'Your edits will be moderated.')

                messages.add_message(
                    request, messages.INFO,
                    'Your edits to %s were saved.' % (entry.ddname))
                return redirect('detail', dd_id=entry.project.dd_id)
            else:
                messages.add_message(
                    request, messages.INFO,
                    "There were errors in your submission: %s" %
                    (updated_project.errors))
                return redirect('update', dd_id=project.dd_id)

        else:
            project = ModeratedProjectForm(
                instance=ModeratedProject.new_from_project(project))

    else:
        messages.add_message(
            request, messages.INFO,
            'You are not authorized to edit projects outside your municipality.'
        )
        return redirect('detail', dd_id=dd_id)

    return render_to_response('development/update.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #36
0
from __future__ import unicode_literals
Example #37
0
 def convert(self, value):
     from django.contrib.gis.geos import GEOSGeometry
     srid = value.get('srid')
     value = GEOSGeometry(json.dumps(value))
     value.srid = srid
     return value
Example #38
0
        path = argv[1]
    except IndexError:
        print("Requires filename")
        exit(1)

    reader = GDALDatasetEnvisatMetadataFormatReader(env)
    ds = gdal.Open(path)

    if not ds:
        print("Cannot open '%s' as GDAL Dataset." % path)
        exit(1)
    elif not reader.test_ds(ds):
        print("Dataset '%s' does not contain required ENVISAT metadata." %
              path)
        exit(1)

    md = reader.read_ds(ds)
    del ds

    footprint = GEOSGeometry(get_footprint_wkt(ds))
    footprint.srid = 4326

    encoder = EOP20Encoder()

    xml = encoder.serialize(
        encoder.encode_earth_observation(EOMetadata(footprint=footprint,
                                                    **md)))

    with open(os.path.join(os.path.dirname(path))) as f:
        f.write(xml)
Example #39
0
    
    return datetime(year, month, day, hour, minute, second)

if __name__=="__main__":
    path = argv[1]

    ds = gdal.Open(path)
    
    eo_id = os.path.splitext(os.path.basename(path))[0]
    begin_time = parse_timestamp(ds.GetMetadataItem("MPH_SENSING_START"))
    end_time = parse_timestamp(ds.GetMetadataItem("MPH_SENSING_STOP"))
    
    del ds

    footprint = GEOSGeometry(get_footprint_wkt(path))
    footprint.srid = 4326

    encoder = EOPEncoder()  
    
    xml = DOMElementToXML(
        encoder.encodeEarthObservation(
            eo_id,
            begin_time,
            end_time,
            footprint
        )
    )
  
    xml_file = open(os.path.join(os.path.dirname(path), "%s.xml" % eo_id), "w")
    xml_file.write(xml)
    xml_file.close()
Example #40
0
 def convert(self, value):
     from django.contrib.gis.geos import GEOSGeometry
     srid = value.get('srid')
     value = GEOSGeometry(json.dumps(value))
     value.srid = srid
     return value
Example #41
0
def update(request, dd_id):
    """ Update existing project """

    try:
        project = Project.objects.transform(4326).get(pk=dd_id)
    except Project.DoesNotExist:
        raise Http404

    # TODO: refactor this whole block

    if has_permissions(request.user, project.taz.municipality):     

        user = request.user.profile

        if request.method == 'POST':
            mod_proj = ModeratedProject.new_from_project(project)
            mod_proj.user = request.user

            updated_project = ModeratedProjectForm(request.POST, instance=mod_proj)
            
            if updated_project.is_valid():
                entry = updated_project.save(commit=False)
                new_location = GEOSGeometry(entry.location)
                new_location.srid = 4326
                new_location.transform(26986)

                entry.location = new_location

                entry.save(user=request.user, update_walkscore=True)

                if user.is_trusted() or user.is_municipal():
                    # TODO: refactor
                    entry.accept()
                    municipal_users = User.objects.filter(profile__municipality=entry.municipality())
                    emails = [ user.email for user in municipal_users ]
                    
                    body = get_template('mail_templates/new_published_edit.html').render(
                        Context({
                            'project_id' : entry.project.dd_id,
                            'project_name' : entry.project.ddname,
                            'municipality_name' : entry.municipality().name,
                            'project': entry,
                            'domain': request.META['HTTP_HOST'],
                       })
                    )

                    send_mail(
                        'Development Database: New Published Edit',
                        body,
                        emails.pop(),
                        emails,
                        fail_silently=False)
                    
                    messages.add_message(request, messages.INFO, 'You are a trusted user, so your edits will be published immediately.')
                else:
                    # TODO: refactor
                    municipal_users = User.objects.filter(profile__municipality=entry.municipality())
                    emails = [ user.email for user in municipal_users ]
                    
                    body = get_template('mail_templates/new_pending_edit.html').render(
                        Context({
                            'project_id' : entry.project.dd_id,
                            'project_name' : entry.project.ddname,
                            'municipality_name' : entry.municipality().name,
                            'project': entry,
                            'domain': request.META['HTTP_HOST'],
                       })
                    )

                    send_mail(
                        'Development Database: New Pending Edit',
                        body,
                        emails.pop(),
                        emails,
                        fail_silently=False)

                    messages.add_message(request, messages.INFO, 'Your edits will be moderated.')
                    
                messages.add_message(request, messages.INFO, 'Your edits to %s were saved.' % (entry.ddname) )
                return redirect('detail', dd_id=entry.project.dd_id)
            else:
                messages.add_message(request, messages.INFO, "There were errors in your submission: %s" % (updated_project.errors))
                return redirect('update', dd_id=project.dd_id)

        else:
            project = ModeratedProjectForm(instance=ModeratedProject.new_from_project(project))

    else:
        messages.add_message(request, messages.INFO, 'You are not authorized to edit projects outside your municipality.' )
        return redirect('detail', dd_id=dd_id)

    return render_to_response('development/update.html', locals(), context_instance=RequestContext(request))
Example #42
0
def addRunlet(run, old, new):

    if ((old.lat == new.lat) and (old.lon == new.lon)
            and (run['runlets'] == 0)):
        return

    path_id = getNearestPath(old)

    if (path_id == None):
        path_id = -1

    old_lat = old.lat
    old_lon = old.lon
    t0 = old.t

    new_lat = new.lat
    new_lon = new.lon
    tn = new.t

    if (old.dirTag != new.dirTag):
        old_lat = new_lat
        old_lon = new_lon
        t0 = tn

    sql = "insert into runlet (run_id,lat0,lon0,loc0,t0,latn,lonn,locn,tn,path_id,distance) values (" + str(
        run['id']) + "," + str(old_lat) + "," + str(
            old_lon) + ", ST_SetSRID(ST_MakePoint(" + str(old_lon) + "," + str(
                old_lat
            ) + " )," + srid + ")," + str(t0) + "," + str(new_lat) + "," + str(
                new_lon) + ",ST_SetSRID(ST_MakePoint(" + str(
                    new_lon) + "," + str(new_lat) + " )," + srid + ") ," + str(
                        tn) + "," + str(path_id) + ",0) returning id"

    cur = old.db.cursor()
    cur.execute(sql)
    old.db.commit()
    id = cur.fetchone()[0]

    GEOSGeom0 = GEOSGeometry("POINT(" + str(old.lon) + " " + str(old.lat) +
                             ")")
    GEOSGeom0.srid = 4326
    GEOSGeomn = GEOSGeometry("POINT(" + str(new.lon) + " " + str(new.lat) +
                             ")")
    GEOSGeomn.srid = 4326
    GEOSGeom0.transform(ct)
    GEOSGeomn.transform(ct)
    dist = GEOSGeom0.distance(GEOSGeomn)
    sql = "update runlet set distance=%s where id=%s"
    cur.execute(sql, (
        dist,
        id,
    ))
    old.db.commit()

    freq = int((t - run['startTime']) / (run['runlets'] + 1))

    sql = "update run set distance =  distance + %s, runlets = runlets + 1, freq = %s where id = " + str(
        run['id'])
    cur.execute(sql, (
        dist,
        freq,
    ))
    old.db.commit()
    """