Example #1
0
def annotations(request, mapid, id=None):
    geoj = GeoJSON.GeoJSON()
    if id != None:
        obj = MapNote.objects.get(pk=id)
        map_obj = Map.objects.get(id=mapid)
        if request.method == "DELETE":
            if request.user.id == obj.owner_id or request.user.has_perm(
                    'maps.change_map', obj=map_obj):
                obj.delete()
                return HttpResponse(status=200)
            else:
                return HttpResponse(status=403)
        elif request.method != "GET":
            if request.user.id == obj.owner_id:
                features = geoj.decode(request.raw_post_data)
                obj = applyGeometry(obj, features[0])
            else:
                return HttpResponse(status=403)
        return HttpResponse(serialize([obj], ['title', 'content', 'owner_id']),
                            status=200)
    if request.method == "GET":
        bbox = [
            float(n) for n in re.findall('[0-9\.\-]+', request.GET["bbox"])
        ]
        features = MapNote.objects.filter(
            map=Map.objects.get(pk=mapid),
            geometry__intersects=Envelope(bbox).wkt)
    else:
        if request.user.id is not None:
            features = geoj.decode(request.raw_post_data)
            created_features = []
            for feature in features:
                obj = MapNote(map=Map.objects.get(id=mapid),
                              owner=request.user)
                obj = applyGeometry(obj, feature)
                created_features.append(obj)
            features = created_features
        else:
            return HttpResponse(status=301)
    data = serialize(features, ['title', 'content', 'owner_id'])
    if 'callback' in request.REQUEST:
        data = '%s(%s);' % (request.REQUEST['callback'], data)
        return HttpResponse(data, "text/javascript")
    return HttpResponse(data, "application/json")
Example #2
0
def wfabbaLayer(request, start, end):

    url = 'http://geonode.terravisiongeo.com.br/geoserver/geonode/ows?service=WFS&version=1.0.0&'
    url += 'request=GetFeature&typeName=geonode:_2ferr004_ger_pl_zoneamento_buffer&outputFormat=application/json'

    ds = DataSource(url)

    layer = ds[0]
    bounds = Envelope(layer.extent.tuple)

    dataRef1 = datetime.fromtimestamp(int(start) / 1000)
    dataRef2 = datetime.fromtimestamp(int(end) / 1000)

    query = FocoWFABBA.objects\
        .filter(dataUTC__range= (dataRef1, dataRef2))\
        .filter(posicao__intersects=bounds.wkt)
    geojson_data = GeoJSONSerializer().serialize(query, use_natural_keys=True)

    return HttpResponse(geojson_data, content_type='text/javascript')
Example #3
0
    def import_district(self):
        uptodate = self.download_once('city')
        if uptodate and not self.force:
            return

        data = self.get_data('city')

        total = sum(1 for _ in data)

        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()
        self.build_hierarchy()

        self.logger.info("Building city index")
        city_index = {}
        for obj in City.objects.all():
            city_index[obj.id] = obj

        self.logger.info("Importing district data")
        for item in tqdm(data, total=total, desc="Importing districts"):
            if not self.call_hook('district_pre', item):
                continue

            type = item['featureCode']
            if type not in district_types:
                continue

            district = District()
            district.name = item['name']
            district.name_std = item['asciiName']
            district.slug = slugify(district.name_std)
            district.location = Point(float(item['longitude']),
                                      float(item['latitude']))
            district.population = int(item['population'])

            # Find city
            city = None
            try:
                city = city_index[self.hierarchy[district.id]]
            except:
                self.logger.warning(
                    "District: %s: Cannot find city in hierarchy, using nearest",
                    district.name)
                city_pop_min = 100000
                # we are going to try to find closet city using native
                # database .distance(...) query but if that fails then
                # we fall back to degree search, MYSQL has no support
                # and Spatialite with SRID 4236.
                try:
                    city = City.objects.filter(
                        population__gt=city_pop_min).distance(
                            district.location).order_by('distance')[0]
                except:
                    self.logger.warning(
                        "District: %s: DB backend does not support native '.distance(...)' query "
                        "falling back to two degree search", district.name)
                    search_deg = 2
                    min_dist = float('inf')
                    bounds = Envelope(district.location.x - search_deg,
                                      district.location.y - search_deg,
                                      district.location.x + search_deg,
                                      district.location.y + search_deg)
                    for e in City.objects.filter(
                            population__gt=city_pop_min).filter(
                                location__intersects=bounds.wkt):
                        dist = geo_distance(district.location, e.location)
                        if dist < min_dist:
                            min_dist = dist
                            city = e

            if not city:
                self.logger.warning(
                    "District: %s: Cannot find city -- skipping",
                    district.name)
                continue

            district.city = city

            if not self.call_hook('district_post', district, item):
                continue
            district.save()
            self.logger.debug("Added district: %s", district)
Example #4
0
 def extent(self):
     "Returns the extent (an Envelope) of this layer."
     env = OGREnvelope()
     capi.get_extent(self.ptr, byref(env), 1)
     return Envelope(env)
Example #5
0
 def envelope(self):
     "Returns the envelope for this Geometry."
     # TODO: Fix Envelope() for Point geometries.
     return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope())))
Example #6
0
    def import_district(self):
        self.download('city')
        data = self.get_data('city')

        total = sum(1 for _ in data)

        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()
        self.build_hierarchy()

        city_index = {}
        for obj in tqdm(City.objects.all(), total=City.objects.all().count(),
                        desc="Building city index"):
            city_index[obj.id] = obj

        for item in tqdm(data, total=total, desc="Importing districts"):
            if not self.call_hook('district_pre', item):
                continue

            _type = item['featureCode']
            if _type not in district_types:
                continue

            defaults = {
                'name': item['name'],
                'name_std': item['asciiName'],
                'location': Point(float(item['longitude']), float(item['latitude'])),
                'population': int(item['population']),
            }

            if hasattr(District, 'code'):
                defaults['code'] = item['admin3Code'],

            geonameid = int(item['geonameid'])

            # Find city
            city = None
            try:
                city = city_index[self.hierarchy[geonameid]]
            except KeyError:
                self.logger.debug("District: %d %s: Cannot find city in hierarchy, using nearest", geonameid, defaults['name'])
                city_pop_min = 100000
                # we are going to try to find closet city using native
                # database .distance(...) query but if that fails then
                # we fall back to degree search, MYSQL has no support
                # and Spatialite with SRID 4236.
                try:
                    if django_version < (1, 9):
                        city = City.objects.filter(population__gt=city_pop_min)\
                                   .distance(defaults['location'])\
                                   .order_by('distance')[0]
                    else:
                        city = City.objects.filter(
                            location__distance_lte=(defaults['location'], D(km=1000))
                        ).annotate(
                            distance=Distance('location', defaults['location'])
                        ).order_by('distance').first()
                except City.DoesNotExist as e:
                    self.logger.warning(
                        "District: %s: DB backend does not support native '.distance(...)' query "
                        "falling back to two degree search",
                        defaults['name']
                    )
                    search_deg = 2
                    min_dist = float('inf')
                    bounds = Envelope(
                        defaults['location'].x - search_deg, defaults['location'].y - search_deg,
                        defaults['location'].x + search_deg, defaults['location'].y + search_deg)
                    for e in City.objects.filter(population__gt=city_pop_min).filter(
                            location__intersects=bounds.wkt):
                        dist = geo_distance(defaults['location'], e.location)
                        if dist < min_dist:
                            min_dist = dist
                            city = e
            else:
                self.logger.debug("Found city in hierarchy: %s [%d]", city.name, geonameid)

            if not city:
                self.logger.warning("District: %s: Cannot find city -- skipping", defaults['name'])
                continue

            defaults['city'] = city

            try:
                with transaction.atomic():
                    district = District.objects.get(city=defaults['city'], name=defaults['name'])
            except District.DoesNotExist:
                # If the district doesn't exist, create it with the geonameid
                # as its id
                district, created = District.objects.update_or_create(id=item['geonameid'], defaults=defaults)
            else:
                # Since the district already exists, but doesn't have its
                # geonameid as its id, we need to update all of its attributes
                # *except* for its id
                for key, value in defaults.items():
                    setattr(district, key, value)
                district.save()
                created = False

            if not self.call_hook('district_post', district, item):
                continue

            self.logger.debug("%s district: %s", "Added" if created else "Updated", district)
Example #7
0
    def import_district(self):
        uptodate = self.download_once('city')
        if uptodate and not self.force: return
        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()
        self.build_hierarchy()

        self.logger.info("Building city index")
        city_index = {}
        for obj in City.objects.all():
            city_index[obj.id] = obj

        self.logger.info("Importing district data")
        for items in self.parse(data):
            if not self.call_hook('district_pre', items): continue

            type = items[7]
            if type not in district_types: continue

            district = self.import_city_common(District(), items)
            if not district: continue

            # Find city
            city = None
            try:
                city = city_index[self.hierarchy[district.id]]
            except:
                self.logger.warning(
                    "District: {}: Cannot find city in hierarchy, using nearest"
                    .format(district.name))
                city_pop_min = 100000
                if connection.ops.mysql:
                    # mysql doesn't have distance function, get nearest city within 2 degrees
                    search_deg = 2
                    min_dist = float('inf')
                    bounds = Envelope(district.location.x - search_deg,
                                      district.location.y - search_deg,
                                      district.location.x + search_deg,
                                      district.location.y + search_deg)
                    for e in City.objects.filter(
                            population__gt=city_pop_min).filter(
                                location__intersects=bounds.wkt):
                        dist = geo_distance(district.location, e.location)
                        if dist < min_dist:
                            min_dist = dist
                            city = e
                else:
                    city = City.objects.filter(
                        population__gt=city_pop_min).distance(
                            district.location).order_by('distance')[0]
            if not city:
                self.logger.warning(
                    "District: {}: Cannot find city -- skipping".format(
                        district.name))
                continue
            district.city = city

            if not self.call_hook('district_post', district, items): continue
            district.save()
            self.logger.debug("Added district: {}".format(district))
Example #8
0
    def import_district(self):
        uptodate = self.download_once('city')
        if uptodate and not self.force: return
        data = self.get_data('city')

        self.build_country_index()
        self.build_region_index()
        self.build_hierarchy()

        self.logger.info("Building city index")
        city_index = {}
        for obj in City.objects.all():
            city_index[obj.id] = obj

        self.logger.info("Importing district data")
        for items in self.parse(data):
            if not self.call_hook('district_pre', items): continue

            type = items[7]
            if type not in district_types: continue

            district = self.import_city_common(District(), items)
            if not district: continue

            # Find city
            city = None
            try:
                city = city_index[self.hierarchy[district.id]]
            except:
                self.logger.warning(
                    "District: {0}: Cannot find city in hierarchy, using nearest"
                    .format(district.name))
                city_pop_min = 100000
                # we are going to try to find closet city using native database .distance(...) query but if that fails
                # then we fall back to degree search, MYSQL has no support and Spatialite with SRID 4236.
                try:
                    city = City.objects.filter(
                        population__gt=city_pop_min).distance(
                            district.location).order_by('distance')[0]
                except:
                    self.logger.warning("District: {0}: DB backend does not support native '.distance(...)' query " \
                                        "falling back to two degree search".format(district.name))
                    search_deg = 2
                    min_dist = float('inf')
                    bounds = Envelope(district.location.x - search_deg,
                                      district.location.y - search_deg,
                                      district.location.x + search_deg,
                                      district.location.y + search_deg)
                    for e in City.objects.filter(
                            population__gt=city_pop_min).filter(
                                location__intersects=bounds.wkt):
                        dist = geo_distance(district.location, e.location)
                        if dist < min_dist:
                            min_dist = dist
                            city = e

            if not city:
                self.logger.warning(
                    "District: {0}: Cannot find city -- skipping".format(
                        district.name))
                continue
            district.city = city

            if not self.call_hook('district_post', district, items): continue
            district.save()
            self.logger.debug("Added district: {0}".format(district))
Example #9
0
<<<<<<< HEAD
        "Returns the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise."
=======
        "Return the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        return capi.get_area(self.ptr)

    @property
    def envelope(self):
<<<<<<< HEAD
        "Returns the envelope for this Geometry."
=======
        "Return the envelope for this Geometry."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        # TODO: Fix Envelope() for Point geometries.
        return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope())))

    @property
    def empty(self):
        return capi.is_empty(self.ptr)

    @property
    def extent(self):
<<<<<<< HEAD
        "Returns the envelope as a 4-tuple, instead of as an Envelope object."
=======
        "Return the envelope as a 4-tuple, instead of as an Envelope object."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        return self.envelope.tuple

    # #### SpatialReference-related Properties ####
Example #10
0
=======
        # Should have returned a Feature, raise an IndexError.
        raise IndexError('Invalid feature id: %s.' % feat_id)
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435

    # #### Layer properties ####
    @property
    def extent(self):
<<<<<<< HEAD
        "Returns the extent (an Envelope) of this layer."
=======
        "Return the extent (an Envelope) of this layer."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        env = OGREnvelope()
        capi.get_extent(self.ptr, byref(env), 1)
        return Envelope(env)

    @property
    def name(self):
<<<<<<< HEAD
        "Returns the name of this layer in the Data Source."
=======
        "Return the name of this layer in the Data Source."
>>>>>>> 37c99181c9a6b95433d60f8c8ef9af5731096435
        name = capi.get_fd_name(self._ldefn)
        return force_text(name, self._ds.encoding, strings_only=True)

    @property
    def num_feat(self, force=1):
<<<<<<< HEAD
        "Returns the number of features in the Layer."