Exemplo n.º 1
0
    def save(self, *args, **kwargs):
        if self.extent_lat_min is not None and self.extent_long_min is not None and self.extent_lat_max is not None and \
                        self.extent_long_max is not None:
            self.geometry = Polygon.from_bbox((self.extent_long_min, self.extent_lat_min,
                                               self.extent_long_max, self.extent_lat_max))

        super(Project, self).save(*args, **kwargs)
def new_item(request):
    if request.method == 'POST':
        item_json_obj = json.loads(request.POST['map-json'])
        item_obj = Item()
        item_obj.owner = request.user
        item_obj.name = item_json_obj['name']
        item_obj.title = item_json_obj['title']
        item_obj.url = item_json_obj['url']
        item_obj.type = item_json_obj['type']
        item_obj.type_keywords = ",".join(item_json_obj['typeKeywords'])
        item_obj.description = item_json_obj['description']
        item_obj.tags = ",".join(item_json_obj['tags'])
        item_obj.snippet = item_json_obj['snippet']
        item_obj.thumbnail = item_json_obj['thumbnail']
        if item_json_obj['extent']:
            item_obj.extent = Polygon.from_bbox(item_json_obj['extent'][0] +
                                                item_json_obj['extent'][1])

        item_obj.created = datetime.datetime.today()
        item_obj.modified = datetime.datetime.today()

        item_obj.save()

        if 'text' in item_json_obj:
            item_data_obj = ItemData(item=item_obj,
                                     text=json.dumps(item_json_obj['text']))
            item_data_obj.save()
        return redirect(reverse('content.edit_item', args=[item_obj.id]))
    else:
        return render(request, 'content/edit_item.html')
Exemplo n.º 3
0
def rack_requested_kml(request):
    try:
        page_number = int(request.REQUEST.get('page_number', '1'))
    except ValueError:
        page_number = 1
    try:
        page_size = int(request.REQUEST.get('page_size', sys.maxint))
    except ValueError:
        page_size = sys.maxint
    # Get bounds from request.
    bbox = request.REQUEST.get('bbox')
    if bbox:
        bbox = [float(n) for n in bbox.split(',')]
        assert len(bbox) == 4
        geom = Polygon.from_bbox(bbox)
        racks = Rack.objects.filter(location__contained=geom)
    else:
        racks = Rack.objects.all()
    racks = racks.order_by(*DEFAULT_RACK_ORDER)
    paginator = Paginator(racks, page_size)
    page_number = min(page_number, paginator.num_pages)
    page = paginator.page(page_number)
    return render_to_kml("placemarkers.kml", {'racks' : racks,
                                              'page': page,
                                              'page_size': page_size,
                                              }) 
Exemplo n.º 4
0
def build_proposal_query_dict(d):
    subqueries = {}
    ids = build_attributes_query(d) or []

    if "id" in d:
        ids = re.split(r"\s*,\s*", d["id"])

    if "text" in d:
        subqueries["address__icontains"] = d["text"]

    if d.get("region"):
        regions = re.split(r"\s*,\s*", d["region"])
        regions = [region_names[r] for r in regions if r in region_names]
        if len(regions) == 1:
            subqueries["region_name"] = regions[0]
        else:
            subqueries["region_name__in"] = regions

    if ids:
        subqueries["pk__in"] = ids

    if "projects" in d:
        if d["projects"] == "null":
            subqueries["project__isnull"] = True
        elif d["projects"] == "all":
            subqueries["project__isnull"] = False
        # else:
        #     subqueries["projects"] = d["project"]

    bounds = d.get("box")
    if bounds:
        coords = [float(coord) for coord in bounds.split(",")]
        # Coordinates are submitted to the server as
        # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a
        # different order:
        bbox = Polygon.from_bbox((coords[1], coords[0],
                                  coords[3], coords[2]))
        subqueries["location__within"] = bbox

    # If status is anything other than 'active' or 'closed', find all
    # proposals.
    status = d.get("status", "active").lower()
    if status == "closed":
        subqueries["complete"] = True
    elif status == "active":
        subqueries["complete"] = False

    event = d.get("event")
    if event:
        try:
            subqueries["event"] = int(event)
        except ValueError:
            pass

    for k in d:
        if k in query_params:
            subqueries[query_params[k]] = d[k]

    return subqueries
Exemplo n.º 5
0
    def handle(self, *args, **options):
        verbosity = options.get('verbosity')
        file_path = options.get('file_path')
        area_type_name = options.get('area_type')
        name_column = options.get('name')
        encoding = options.get('encoding')
        srid = options.get('srid')
        do_intersect = options.get('intersect')
        bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT)
        bbox.srid = settings.SRID
        ds = DataSource(file_path, encoding=encoding)
        count_error = 0
        area_type, created = RestrictedAreaType.objects.get_or_create(
            name=area_type_name)
        if verbosity > 0:
            self.stdout.write("RestrictedArea Type's %s created" %
                              area_type_name if created else "Get %s" %
                              area_type_name)

        for layer in ds:
            for feat in layer:
                try:
                    geom = feat.geom.geos
                    if not isinstance(geom, Polygon) and not isinstance(
                            geom, MultiPolygon):
                        if verbosity > 0:
                            self.stdout.write(
                                "%s's geometry is not a polygon" %
                                feat.get(name_column))
                        break
                    elif isinstance(geom, Polygon):
                        geom = MultiPolygon(geom)
                    self.check_srid(srid, geom)
                    geom.dim = 2
                    if geom.valid:
                        if do_intersect and bbox.intersects(
                                geom) or not do_intersect and geom.within(
                                    bbox):
                            instance, created = RestrictedArea.objects.update_or_create(
                                name=feat.get(name_column),
                                area_type=area_type,
                                defaults={'geom': geom})
                            if verbosity > 0:
                                self.stdout.write(
                                    "%s %s" %
                                    ('Created' if created else 'Updated',
                                     feat.get(name_column)))
                    else:
                        if verbosity > 0:
                            self.stdout.write("%s's geometry is not valid" %
                                              feat.get(name_column))
                except IndexError:
                    if count_error == 0:
                        self.stdout.write(
                            "Name's attribute do not correspond with options\n"
                            "Please, use --name to fix it.\n"
                            "Fields in your file are : %s" %
                            ', '.join(layer.fields))
                    count_error += 1
Exemplo n.º 6
0
def build_proposal_query_dict(d):
    subqueries = {}
    ids = run_attributes_query(d) or []

    if "id" in d:
        ids = re.split(r"\s*,\s*", d["id"])

    if "text" in d:
        subqueries["address__icontains"] = d["text"]

    if d.get("region"):
        regions = re.split(r"\s*;\s*", d["region"])
        subqueries["region_name__in"] = regions

    if ids:
        subqueries["pk__in"] = ids

    if "projects" in d:
        if d["projects"] == "null":
            subqueries["project__isnull"] = True
        elif d["projects"] == "all":
            subqueries["project__isnull"] = False

    if "lotsize" in d:
        parcel_query = make_size_query(d["lotsize"])
        if parcel_query:
            parcel_ids = LotSize.objects.filter(
                **parcel_query).values("parcel_id")
            subqueries["parcel_id__in"] = parcel_ids

    bounds = d.get("box")
    if bounds:
        coords = [float(coord) for coord in bounds.split(",")]
        # Coordinates are submitted to the server as
        # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a
        # different order:
        bbox = Polygon.from_bbox((coords[1], coords[0], coords[3], coords[2]))
        subqueries["location__within"] = bbox

    # If status is anything other than 'active' or 'closed', find all
    # proposals.
    status = d.get("status", "active").lower()
    if status == "closed":
        subqueries["complete"] = True
    elif status == "active":
        subqueries["complete"] = False

    event = d.get("event")
    if event:
        try:
            subqueries["event"] = int(event)
        except ValueError:
            pass

    for k in d:
        if k in query_params:
            subqueries[query_params[k]] = d[k]

    return subqueries
Exemplo n.º 7
0
    def apply_filters(self, request, applicable_filters):
        """Apply the filters"""
        if 'location__contained' in applicable_filters:
            area = applicable_filters.pop('location__contained')
            poly = Polygon.from_bbox(area)
            applicable_filters['location__contained'] = poly

        return super(SampleResource, self).apply_filters(request, applicable_filters)
 def _computed_domain(self):
     xmin, ymin, xmax, ymax = (
         wrap_longitude_degrees(self.central_meridian_longitude_degrees - self.MAX_LONGITUDE_OFFSET),
         -90,
         wrap_longitude_degrees(self.central_meridian_longitude_degrees + self.MAX_LONGITUDE_OFFSET),
         90,
     )
     if xmin <= xmax:
         domain = Polygon.from_bbox((xmin, ymin, xmax, ymax))
         domain.srid = WGS_84
         return domain
     else:
         # cut at idealized international date line
         return MultiPolygon(
             Polygon.from_bbox((xmin, ymin, MAX_LONGITUDE_DEGREES, ymax)),
             Polygon.from_bbox((MIN_LONGITUDE_DEGREES, ymin, xmax, ymax)),
             srid=WGS_84,
         )
Exemplo n.º 9
0
def cityracks_kml(request):
    bbox = request.REQUEST.get('bbox')
    if bbox:
        bbox = [float(n) for n in bbox.split(',')]
        assert len(bbox) == 4
        geom = Polygon.from_bbox(bbox)
        cityracks = CityRack.objects.filter(the_geom__within=geom)
    else:
        cityracks = CityRack.objects.all()
    return render_to_kml('cityracks.kml',
                         {'cityracks': cityracks})
Exemplo n.º 10
0
def by_bbox(bbox_string):
    bbox = bbox_string.split(",")

    if len(bbox) != 4:
        raise InvalidSpatialParameterException("The bbox parameter must contain 4 items: xmin, ymin, xmax, ymax")

    try:
        bbox = map(float, bbox)
    except ValueError:
        raise InvalidSpatialParameterException("Items in the bbox parameter must be parseable as floats")

    return {"geom__intersects": Polygon.from_bbox(bbox)}
Exemplo n.º 11
0
def get_geom(point, len_m):
    if type(point).__name__ == 'str':
        point = str_to_point(point)
    k_lat = 0.000009
    k_long = 0.000013
    top_lat = point[0] + (len_m * k_lat)
    top_long = point[1] - (len_m * k_long)
    bot_lat = point[0] - (len_m * k_lat)
    bot_long = point[1] + (len_m * k_long)
    bbox = (top_lat, top_long, bot_lat, bot_long)
    # print('get_geom',bbox)
    return Polygon.from_bbox(bbox)
Exemplo n.º 12
0
def rack_search_kml(request):
    racks = Rack.objects.all()
    try:
        page_number = int(request.REQUEST.get('page_number', '1'))
    except ValueError:
        page_number = 1
    try:
        page_size = int(request.REQUEST.get('page_size', sys.maxint))
    except ValueError:
        page_size = sys.maxint

    status = request.GET.get('status')
    if status:
        racks = racks.filter(status=status)

    verified = request.GET.get('verified')
    if verified:
        racks = Rack.objects.filter_by_verified(verified, racks)

    # Get bounds from request.
    bbox = request.REQUEST.get('bbox')
    if bbox:
        bbox = [float(n) for n in bbox.split(',')]
        assert len(bbox) == 4
        geom = Polygon.from_bbox(bbox)
        racks = racks.filter(location__within=geom)
    cb = request.GET.get('cb')
    boro = request.GET.get('boro')
    board = None
    borough = None
    if cb is not None:
        try:
            board = CommunityBoard.objects.get(gid=int(cb))
            racks = racks.filter(location__within=board.the_geom)
        except (CommunityBoard.DoesNotExist, ValueError):
            board = None
    if board is None and boro is not None:
        try:
            borough = Borough.objects.get(gid=int(boro))
            racks = racks.filter(location__within=borough.the_geom)
        except (CommunityBoard.DoesNotExist, ValueError):
            pass
    racks = racks.order_by(*DEFAULT_RACK_ORDER)
    paginator = Paginator(racks, page_size)
    page_number = min(page_number, paginator.num_pages)
    page = paginator.page(page_number)
    votes = Vote.objects.get_scores_in_bulk(racks)
    return render_to_kml("placemarkers.kml", {'racks' : racks,
                                              'page': page,
                                              'page_size': page_size,
                                              'votes': votes,
                                              })
Exemplo n.º 13
0
 def get_queryset(self):
     queryset = MapData.objects.all()
     bbox = self.request.GET.get('bbox', None)
     if bbox:
         bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')])
         queryset = filter_by_bounds(queryset, bbox)
     zoom = self.request.GET.get('zoom', None)
     if zoom:
         # We order by -length so that the geometries are in that
         # order when rendered by OpenLayers -- this creates the
         # correct stacking order.
         queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length')
     return queryset
Exemplo n.º 14
0
 def get_queryset(self):
     queryset = MapData.objects.all()
     bbox = self.request.GET.get('bbox', None)
     if bbox:
         bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')])
         queryset = filter_by_bounds(queryset, bbox)
     zoom = self.request.GET.get('zoom', None)
     if zoom:
         # We order by -length so that the geometries are in that
         # order when rendered by OpenLayers. This creates the
         # correct stacking order.
         queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length')
     return queryset.select_related('page')
Exemplo n.º 15
0
def get_geom2(point, dist):
    if type(point).__name__ == 'str':
        point = str_to_point(point)
    mylat = point[0]
    mylon = point[1]
    dist = dist / 1000
    lon1 = mylon - dist / abs(math.cos(math.radians(mylat)) * 111.0)
    lon2 = mylon + dist / abs(math.cos(math.radians(mylat)) * 111.0)
    lat1 = mylat + (dist / 111.0)
    lat2 = mylat - (dist / 111.0)
    bbox = (lat1, lon1, lat2, lon2)
    # print('get_geom2',bbox)
    return Polygon.from_bbox(bbox)
Exemplo n.º 16
0
 def get_queryset(self):
     queryset = MapData.objects.all()
     bbox = self.request.GET.get("bbox", None)
     if bbox:
         bbox = Polygon.from_bbox([float(x) for x in bbox.split(",")])
         queryset = filter_by_bounds(queryset, bbox)
     zoom = self.request.GET.get("zoom", None)
     if zoom:
         # We order by -length so that the geometries are in that
         # order when rendered by OpenLayers -- this creates the
         # correct stacking order.
         queryset = filter_by_zoom(queryset, int(zoom)).order_by("-length")
     return queryset
Exemplo n.º 17
0
def add_to_catalog (request , resource_form ,app_name , tags  ,extent):

    resource = resource_form.save(commit=False)
    resource.app = App.objects.get(name= app_name)
    resource.created_by = request.user
    resource.last_updated_by = request.user
    resource.save()
    resource.set_tags(tags)
    bbox = (extent[0], extent[1], extent[2], extent[3])
    resource.location_extent = Polygon.from_bbox(bbox)
    resource.save()
    resource_form.save_m2m()

    return resource
Exemplo n.º 18
0
def by_bbox(bbox_string):
    bbox = bbox_string.split(',')

    if len(bbox) != 4:
        raise InvalidSpatialParameterException(
            'The bbox parameter must contain 4 items: xmin, ymin, xmax, ymax')

    try:
        bbox = map(float, bbox)
    except ValueError:
        raise InvalidSpatialParameterException(
            'Items in the bbox parameter must be parseable as floats')

    return {'geom__intersects': Polygon.from_bbox(bbox)}
Exemplo n.º 19
0
 def get_queryset(self):
     queryset = MapData.objects.filter(region=self.get_region())
     # XXX TODO TEMPORARY HACK
     queryset = queryset.exclude(page__pagetagset__tags__slug='zipcode')
     queryset = queryset.exclude(page__pagetagset__tags__slug='supervisorialdistrict')
     bbox = self.request.GET.get('bbox', None)
     if bbox:
         bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')])
         queryset = filter_by_bounds(queryset, bbox)
     zoom = self.request.GET.get('zoom', None)
     if zoom:
         # We order by -length so that the geometries are in that
         # order when rendered by OpenLayers. This creates the
         # correct stacking order.
         queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length')
     return queryset.select_related('page')
Exemplo n.º 20
0
def bounds_from_box(box):
    """Converts a `box` string parameter to a Polygon object. If given a Polygon,
    it is returned unchanged.

    :param box: (str) with the format latMin,longMin,latMax,longMax

    """
    if isinstance(box, Polygon):
        return box

    coords = [float(coord) for coord in box.split(",")]
    assert len(coords) == 4
    # Coordinates are submitted to the server as
    # latMin,longMin,latMax,longMax, but from_bbox wants its arguments in a
    # different order:
    return Polygon.from_bbox((coords[1], coords[0], coords[3], coords[2]))
Exemplo n.º 21
0
 def get_queryset(self):
     queryset = MapData.objects.filter(region=self.get_region())
     # XXX TODO TEMPORARY HACK
     queryset = queryset.exclude(page__pagetagset__tags__slug='zipcode')
     queryset = queryset.exclude(
         page__pagetagset__tags__slug='supervisorialdistrict')
     bbox = self.request.GET.get('bbox', None)
     if bbox:
         bbox = Polygon.from_bbox([float(x) for x in bbox.split(',')])
         queryset = filter_by_bounds(queryset, bbox)
     zoom = self.request.GET.get('zoom', None)
     if zoom:
         # We order by -length so that the geometries are in that
         # order when rendered by OpenLayers. This creates the
         # correct stacking order.
         queryset = filter_by_zoom(queryset, int(zoom)).order_by('-length')
     return queryset.select_related('page')
Exemplo n.º 22
0
def build_proposal_query(d):
    subqueries = {}
    ids = build_attributes_query(d) or []

    if "id" in d:
        ids = re.split(r"\s*,\s*", d["id"])

    if ids:
        subqueries["pk__in"] = ids

    if "project" in d:
        if d["project"] == "null":
            subqueries["project__isnull"] = True
        elif d["project"] == "all":
            subqueries["project__isnull"] = False
        else:
            subqueries["project"] = d["project"]

    bounds = d.get("bounds")
    if bounds:
        coords = [float(coord) for coord in bounds.split(",")]
        bbox = Polygon.from_bbox(*coords, srid=97406)
        subqueries["location__within"] = bbox

    status = d.get("status", "active").lower()
    if status == "closed":
        subqueries["complete"] = True
    elif status == "active":
        subqueries["complete"] = False
    # If status is anything other than 'active' or 'closed', find all
    # proposals.

    event = d.get("event")
    if event:
        try:
            subqueries["event"] = int(event)
        except ValueError:
            pass

    for k in d:
        if k in query_params:
            subqueries[query_params[k]] = d[k]

    return Q(**subqueries)
def edit_item(request, item_id):
    item_obj = Item.objects.get(id=item_id)
    if request.method == 'POST':
        item_json_obj = json.loads(request.POST['map-json'])
        item_obj.owner = request.user
        item_obj.name = item_json_obj['name']
        item_obj.title = item_json_obj['title']
        item_obj.url = item_json_obj['url']
        item_obj.type = item_json_obj['type']
        item_obj.type_keywords = ",".join(item_json_obj['typeKeywords'])
        item_obj.description = item_json_obj['description']
        item_obj.tags = ",".join(item_json_obj['tags'])
        item_obj.snippet = item_json_obj['snippet']
        item_obj.thumbnail = item_json_obj['thumbnail']
        if item_json_obj['extent']:
            item_obj.extent = Polygon.from_bbox(item_json_obj['extent'][0] +
                                                item_json_obj['extent'][1])
        item_obj.modified = datetime.datetime.today()

        item_obj.save()

        if 'text' in item_json_obj:
            item_data_obj = ItemData(item=item_obj,
                                     text=json.dumps(item_json_obj['text']))
            item_data_obj.save()
    # TODO: handle array types in a better way.
    item_obj.type_keywords = item_obj.type_keywords.split(",")
    item_obj.tags = item_obj.tags.split(",")
    # TODO: handle single object instead of removing square brackets from the string.
    fields = [
        'name', 'title', 'url', 'type', 'type_keywords', 'description', 'tags',
        'snippet', 'thumbnail', 'extent'
    ]
    item_json_obj = json.loads(ModelToJson().serialize(
        [item_obj], indent=True, fields=fields).strip("[]\n"))
    try:
        item_json_obj['text'] = json.loads(
            ItemData.objects.get(item_id=item_id).text)
    except:
        pass
    return render(request, 'content/edit_item.html',
                  {'item_obj': json.dumps(item_json_obj, indent=4)})
Exemplo n.º 24
0
    def handle(self, *args, **options):
        verbosity = options.get('verbosity')
        file_path = options.get('file_path')
        area_type_name = options.get('area_type')
        name_column = options.get('name')
        encoding = options.get('encoding')
        srid = options.get('srid')
        do_intersect = options.get('intersect')
        bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT)
        bbox.srid = settings.SRID
        ds = DataSource(file_path, encoding=encoding)
        count_error = 0
        area_type, created = RestrictedAreaType.objects.get_or_create(name=area_type_name)
        if verbosity > 0:
            self.stdout.write("RestrictedArea Type's %s created" % area_type_name if created else "Get %s" % area_type_name)

        for layer in ds:
            for feat in layer:
                try:
                    geom = feat.geom.geos
                    if not isinstance(geom, Polygon) and not isinstance(geom, MultiPolygon):
                        if verbosity > 0:
                            self.stdout.write("%s's geometry is not a polygon" % feat.get(name_column))
                        break
                    elif isinstance(geom, Polygon):
                        geom = MultiPolygon(geom)
                    self.check_srid(srid, geom)
                    geom.dim = 2
                    if do_intersect and bbox.intersects(geom) or not do_intersect and geom.within(bbox):
                        instance, created = RestrictedArea.objects.update_or_create(name=feat.get(name_column),
                                                                                    area_type=area_type,
                                                                                    defaults={
                                                                                        'geom': geom})
                        if verbosity > 0:
                            self.stdout.write("%s %s" % ('Created' if created else 'Updated', feat.get(name_column)))
                except OGRIndexError:
                    if count_error == 0:
                        self.stdout.write(
                            "Name's attribute do not correspond with options\n"
                            "Please, use --name to fix it.\n"
                            "Fields in your file are : %s" % ', '.join(feat.fields))
                    count_error += 1
Exemplo n.º 25
0
class Migration(migrations.Migration):

    dependencies = [
        ('api', '0038_metadatacontact_is_validator'),
    ]

    operations = [
        migrations.RunSQL(
            sql=
            "ALTER TABLE product ADD COLUMN geom2 geometry(MultiPolygon,2056);",
            reverse_sql="ALTER TABLE product DROP COLUMN geom2;"),
        migrations.RunSQL(
            sql=
            "CREATE INDEX IF NOT EXISTS product_geom2_id ON product USING gist (geom2)",
            reverse_sql="DROP INDEX product_geom2_id;"),
        migrations.RunSQL(
            sql="UPDATE product set geom2 = ST_Multi(geom);",
            reverse_sql=
            "UPDATE product set geom = (ST_DUMP(geom2)).geom::geometry(Polygon,2056);"
        ),
        migrations.RunSQL(
            sql="ALTER TABLE product DROP COLUMN geom;",
            reverse_sql=
            "ALTER TABLE product ADD COLUMN geom geometry(Polygon,2056);"),
        migrations.RunSQL(
            sql="ALTER TABLE product RENAME COLUMN geom2 TO geom;",
            reverse_sql="ALTER TABLE product RENAME COLUMN geom TO geom2;",
            state_operations=[
                migrations.AlterField(
                    model_name='product',
                    name='geom',
                    field=MultiPolygonField(default=MultiPolygon(
                        Polygon.from_bbox(
                            (2519900, 1186430, 2578200, 1227030))),
                                            srid=2056,
                                            verbose_name='geom'),
                ),
            ],
        ),
    ]
Exemplo n.º 26
0
def build_proposal_query(d):
    subqueries = {}
    ids = build_attributes_query(d) or []

    pids = d.get("id")
    if pids:
        ids = re.split(r"\s*,\s*", pids)

    if ids:
        subqueries["pk__in"] = ids

    bounds = d.get("bounds")
    if bounds:
        coords = [float(coord) for coord in bounds.split(",")]
        bbox = Polygon.from_bbox(*coords, srid=97406)
        subqueries["location__within"] = bbox

    status = d.get("status", "active").lower()
    if status == "closed":
        subqueries["complete"] = True
    elif status == "active":
        subqueries["complete"] = False
    # If status is anything other than 'active' or 'closed', find all
    # proposals.

    event = d.get("event")
    if event:
        try:
            subqueries["event"] = int(event)
        except ValueError as verr:
            pass

    for k in d:
        if k in query_params:
            subqueries[query_params[k]] = d[k]

    return Q(**subqueries)
Exemplo n.º 27
0
 def make_polybbox(self,bbox):
     return Polygon.from_bbox(bbox)
Exemplo n.º 28
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        # start drawing each block
        pil_map = Image.new("RGBA", (width, height), (255,255,255, 0))
        pil_draw = ImageDraw.Draw(pil_map)
        
        # return empty images
        if zoom < 11:
            return pil_map

        # first, figure out the bounding box of the tile we're rendering
        nw = self.layer.projection.projLocation(ModestMaps.Core.Point(xmin, ymin))
        se = self.layer.projection.projLocation(ModestMaps.Core.Point(xmax, ymax))
        max_lat = max(nw.lat, se.lat)
        min_lat = min(nw.lat, se.lat)
        max_lon = max(nw.lon, se.lon)
        min_lon = min(nw.lon, se.lon)
        
        # Converting polygon to OSGB36 in order to compare with the ones we have in
        # the database
        shp = ShpParser()
        min_p = shp.convert_point_to_OSGB36(min_lat, min_lon)
        max_p = shp.convert_point_to_OSGB36(max_lat, max_lon)
        
        bbox = Polygon.from_bbox((min_p[0], min_p[1], max_p[0], max_p[1]))
        
        # this obj is used to translate between lat/lon and pixel space
        bound1 = ModestMaps.Geo.Location(min_lat, min_lon)
        bound2 = ModestMaps.Geo.Location(max_lat, max_lon)
        mmap = ModestMaps.mapByExtentZoom(self.provider, bound1, bound2, zoom)

        neighbourhoods = False
        polys = None
        max_x = None
        min_x = None
        
        try:
            # If zoom < 15 we draw postcode polygons, otherwise neighbourhoods
            if zoom < 15 or self.type == "None":
                polys = Neighbourhood.objects.filter(poly__intersects=bbox)
                neighbourhoods = True
            else:
                polys = Postcode.objects.filter(poly__intersects=bbox)
                
            print "Painting", polys.count(), "blocks"
            
            # Have to find the city where the polygons belong in
            _city = None
            if self.type != "None":
                for poly in polys:
                    if _city is not None:
                        break
                    if poly.poly and isinstance(poly.poly, geos.MultiPolygon):
                        for inside_poly in poly.poly:
                            if _city is None:
                                # Find the city if we haven't found it yet
                                cities = Council.objects.filter(poly__intersects=inside_poly)
                                if len(cities) > 0:
                                    _city = cities[0].convexhull.name
                                    break
                    else: # Probably unneeded as eventually we only have Multipolygons in our db 
                        if _city is None:
                            # Find the city if we haven't found it yet
                            cities = Council.objects.filter(poly__intersects=inside_poly)
                            if len(cities) > 0:
                                _city = cities[0].convexhull.name
                                break
                        
            print "City:", _city
                
            if len(polys) > 0 and self.type != "None":        
                if neighbourhoods:
                    _name = _city+"_neighbourhood_max_"+self.type
                    max_x = float(Statistics.objects.filter(name=_name).all()[0].stat)
                    _name = _city+"_neighbourhood_min_"+self.type
                    min_x = float(Statistics.objects.filter(name=_name).all()[0].stat)
                else:
                    _name = _city+"_postcode_max_"+self.type
                    max_x = float(Statistics.objects.filter(name=_name).all()[0].stat)
                    _name = _city+"_postcode_min_"+self.type
                    min_x = float(Statistics.objects.filter(name=_name).all()[0].stat)
                        
                print "max:", max_x, "min:", min_x
                          
            # For all the polygons we've retrieved from the database (in OSGB36 format)
            for poly in polys:
                _city = None
                if poly.poly and isinstance(poly.poly, geos.MultiPolygon):
                    for inside_poly in poly.poly:
                        
                        if _city is None:
                            # Find the city if we haven't found it yet
                            cities = Council.objects.filter(poly__intersects=inside_poly)
                            if len(cities) > 0:
                                _city = cities[0].convexhull.name
    
                        self._paint_poly(inside_poly, shp, mmap, pil_draw, _city,
                                         max_x, min_x, neighbourhoods)
                else: # Probably unneeded as eventually we only have Multipolygons in our db 
                    if _city is None:
                        # Find the city if we haven't found it yet
                        cities = Council.objects.filter(poly__intersects=inside_poly)
                        if len(cities) > 0:
                            _city = cities[0].convexhull.name
                    self._paint_poly(poly.poly, shp, mmap, pil_draw, _city,
                                     max_x, min_x, neighbourhoods)
        except Exception, err:
            print err
Exemplo n.º 29
0
def query_args_bbox(bbox_string):
    bbox = bbox_string.split(',')

    return {
        'geom__intersects': Polygon.from_bbox(bbox)
    }
    def publish(self):
        if self.portal_item:
            item_obj = self.portal_item
            item_data_obj = ItemData.objects.get(item=item_obj)
        else:
            item_obj = Item()
            item_data_obj = ItemData()

        # save portal item
        item_obj.owner = self.geonode_map.owner
        item_obj.name = self.geonode_map.title.replace(" ", "_")
        item_obj.title = self.geonode_map.title
        item_obj.url = None
        item_obj.type = "Web Map"
        item_obj.type_keywords = ",".join([
            "ArcGIS Online", "Explorer Web Map", "Map", "Online Map", "Web Map"
        ])
        item_obj.description = self.geonode_map.title
        item_obj.tags = ",".join([
            'map',
        ])  # todo: get tags from geonode
        item_obj.snippet = 'snippet'  # todo
        item_obj.thumbnail = self.geonode_map.thumbnail_url
        m = self.geonode_map
        bbox = [m.bbox_x0, m.bbox_y0, m.bbox_x1, m.bbox_y1]
        item_obj.extent = Polygon.from_bbox(bbox)
        item_obj.save()
        # save item data
        item_data_json = json.loads(render_to_string(ITEM_DATA_JSON_TPL, {}))
        op_layers = []
        site_url = settings.SITEURL
        if site_url.endswith("/"):
            site_url = site_url[:-1]
        wms_url = settings.OGC_SERVER["default"]["PUBLIC_LOCATION"]
        if wms_url.endswith("/"):
            wms_url += "wms"
        else:
            wms_url += "/wms"
        wms_layers = []
        #                [{
        #     "name": layergroup_name,
        #     "title": layergroup_name
        #
        # }]

        for layer_obj in self.geonode_map.layer_set.all().exclude(
                group="background"):
            try:

                featurelayer = FeatureLayer.objects.get(
                    geonode_layer__typename=layer_obj.name)
                fields = []
                for f in featurelayer.fields_defs:
                    fields.append({
                        "fieldName": f["name"],
                        "label": f["alias"],
                        "isEditable": f["editable"],
                        "tooltip": "",
                        "visible": True,
                        "format": None,
                        "stringFieldOption":
                        "textbox"  # TODO chanege according to field type
                    })
                layer_params_obj = json.loads(layer_obj.layer_params)
                title = layer_params_obj.get("title", layer_obj.layer_title)
                op_layers.append({
                    "id": "layer_%d" % layer_obj.id,
                    "layerType": "ArcGISFeatureLayer",
                    "url": site_url + featurelayer.meta_page_url,
                    "visibility": True,
                    "opacity": 0,
                    "mode": 1,
                    "title": title,
                    "popupInfo": {
                        "title": title,
                        "fieldInfos": fields,
                        "description": None,
                        "showAttachments": True,
                        "mediaInfos": []
                    }
                })
                wms_layers.append({"name": layer_obj.name, "title": title})
            except:
                pass
        op_layers.insert(
            0, {
                "id":
                "wms",
                "title":
                "WMS",
                "url":
                wms_url,
                "visibility":
                True,
                "visibleLayers": [layer['name'] for layer in wms_layers],
                "opacity":
                1,
                "type":
                "WMS",
                "layerType":
                "WMS",
                "version":
                "1.1.1",
                "mapUrl":
                wms_url,
                "layers":
                wms_layers,
                "spatialReferences": [
                    3857, 2154, 23030, 23031, 23032, 27561, 27562, 27563,
                    27564, 27571, 27572, 27573, 27574, 3035, 3942, 3948, 4171,
                    4258, 4326, 900913
                ],
                "extent": [[
                    float(self.geonode_map.bbox_x0),
                    float(self.geonode_map.bbox_y0)
                ],
                           [
                               float(self.geonode_map.bbox_x1),
                               float(self.geonode_map.bbox_y1)
                           ]],
                "copyright":
                ""
            })
        item_data_json["operationalLayers"] = op_layers
        item_data_obj.item = item_obj
        item_data_obj.text = json.dumps(item_data_json)
        item_data_obj.save()
        # save map
        self.portal_item = item_obj
        self.edited = False
        self.save()
Exemplo n.º 31
0
 def hydrate_location_extent(self, bundle):
     if 'location_extent' in bundle.data:
         e = bundle.data['location_extent']
         bbox = (e[0],e[1],e[2],e[3])
         bundle.obj.location_extent = Polygon.from_bbox(bbox)
     return bundle