Beispiel #1
0
def counts(request):
    '''Returns impact counts per area as geojson query set'''
    form = CountQueryForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        area = cd['area']
        if area == 'county':  # count by county
            geojson = GeoJSONSerializer().serialize(CountyCount.objects.all())
        else:  # it must be zip
            geojson = GeoJSONSerializer().serialize(ZipCount.objects.all())
        return HttpResponse(geojson, content_type='application/json')
    else:
        return HttpResponseBadRequest('invalid form data')
Beispiel #2
0
    def render_to_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        serializer = GeoJSONSerializer()
        response = self.response_class(**response_kwargs)
        queryset = self.get_queryset()

        options = dict(properties=self.properties,
                       precision=self.precision,
                       simplify=self.simplify,
                       srid=self.srid,
                       geometry_field=self.geometry_field,
                       force2d=self.force2d,
                       bbox=self.bbox,
                       bbox_auto=self.bbox_auto,
                       use_natural_keys=self.use_natural_keys)
        serializer.serialize(
            queryset,
            stream=response,
            ensure_ascii=False,
            crs=self.
            crs,  # in geoJSON crs is deprecated, raises error 36 in ol.source
            **options)
        return response
Beispiel #3
0
def impacts(request):
    '''Querys impacts based on impact type, returns geojson query set'''
    form = ImpactQueryForm(request.GET)
    if form.is_valid():
        cd = form.cleaned_data
        impact_type = cd['impact_type']
        if impact_type != '':
            # serialize by impact_type
            querySet = Impact.objects.filter(impact_type=cd['impact_type'])
            geojson = GeoJSONSerializer().serialize(querySet)
        else:
            # serialize all impacts
            geojson = GeoJSONSerializer().serialize(Impact.objects.all())
        return HttpResponse(geojson, content_type='application/json')
    else:
        return HttpResponseBadRequest('form is invalid')
def visitorMapData(request):
    """
    Suppy data to data table of exit link activity page
    """

    data = json.loads(request.body)  # Extract data from request

    from_datetime = datetime.strptime(
        data['from'], '%Y-%m-%d %H:%M')  # converting to datetime object
    to_datetime = datetime.strptime(
        data['to'], '%Y-%m-%d %H:%M')  # converting to datetime object

    # make datetimes timezone aware
    from_datetime = tz.localize(from_datetime)
    to_datetime = tz.localize(to_datetime)

    # getting visitor spot stats from database
    visitor_spot_stats = VisitorSpot.objects.filter(
        datetime__range=(from_datetime, to_datetime))

    # Converting data to json object
    json_res = GeoJSONSerializer().serialize(visitor_spot_stats,
                                             use_natural_keys=True,
                                             with_modelname=False)

    return JsonResponse(json_res, safe=False)  # sending data
Beispiel #5
0
def all_facilities(request):
    """
	returns all facilities from temp table
	"""
    """
	Why am I using Location_w_efforts? 
	The serializer failed with Location, there might be a bug with the django-geojson plugin
	It is not handling backwards relations
	http://stackoverflow.com/questions/22898547/error-with-geodjango-serializer-and-foreignkey-field
	"""

    #facilities = Location_w_efforts.objects.all()

    #print ('hello')

    Location_w_efforts_temp.objects.all().delete()

    all_health_facilities = EffortInstance.objects.all()

    nearby = 'other'

    for i in all_health_facilities:

        print('printing i')
        print(i.effort_instance_id)
        add_to_Location_w_efforts_tempObj(i, nearby)

    geojson_data = GeoJSONSerializer().serialize(
        Location_w_efforts_temp.objects.all(), use_natural_keys=True)

    return HttpResponse(geojson_data, content_type='application/json')
Beispiel #6
0
    def render_to_response(self, context, **response_kwargs):
        from fbr.settings import BASE_DIR
        import os.path
        cpath = BASE_DIR + '/map_cache/burning_' + self.request.GET[
            'time'] + '.txt'
        if (os.path.exists(cpath)):
            from django.http import HttpResponse
            f = open(cpath, 'r')
            out = f.read()
            f.close()
            return HttpResponse(out, content_type="application/json")
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        serializer = GeoJSONSerializer()
        response = self.response_class(**response_kwargs)
        options = dict(properties=self.properties,
                       srid=self.srid,
                       geometry_field=self.geometry_field,
                       force2d=self.force2d)
        serializer.serialize(self.get_queryset(),
                             stream=response,
                             ensure_ascii=False,
                             **options)

        #import pdb; pdb.set_trace()
        #f = open(cpath,'w')
        #f.write(response.content)
        #f.close()
        return response
Beispiel #7
0
def keep_track_save(sender, instance, created, **kwargs):
    action = 'save' if created else 'update'
    if settings.CSW_T == True and sender == WetlandLayer and instance.publishable == True:
        create_update_csw(instance, action)
    if settings.ELASTICSEARCH == True and (
            sender == WetlandLayer
            or sender == ExternalLayer) and instance.publishable == True:
        instance.indexing()
    if settings.ELASTICSEARCH == True and sender == ExternalDatabase:
        instance.indexing()
    if settings.ELASTICSEARCH == True and sender == Wetland:
        instance.indexing()
        ext_db = ExternalDatabase.objects.filter(wetland_id=instance.id)
        wetland_layer = WetlandLayer.objects.filter(wetland_id=instance.id,
                                                    publishable=True)
        for x in ext_db:
            x.indexing()
        for y in wetland_layer:
            y.indexing()
    if sender == Wetland:
        #update wetlands.geojson
        f = open(settings.MEDIA_ROOT + 'wetlands/wetlands.geojson', 'w')
        geojson = GeoJSONSerializer().serialize(
            Wetland.objects.all(),
            geometry_field='geom',
            properties=('id', 'name', 'country', 'geo_scale', 'size',
                        'description', 'ecoregion', 'wetland_type',
                        'site_type', 'products'),
            precision=4)
        f.write(geojson)
Beispiel #8
0
 def get_context_data(self, **kwargs):
     current_object = self.get_object()
     geojson = GeoJSONSerializer().serialize(
         [
             current_object,
         ],
         geometry_field='coordonnees_geographiques',
         properties=('nom', 'description', 'commune_label',
                     'short_description', 'feature', 'url', 'state'))
     context = super(ProjectDetailView, self).get_context_data(**kwargs)
     context['geojson'] = geojson
     context['form'] = GlobalProjectForm
     FormSet = inlineformset_factory(Project,
                                     PartenaireDetail,
                                     fields='__all__',
                                     can_delete=True,
                                     extra=1)
     context['formset'] = FormSet(instance=current_object)
     FormSet2 = inlineformset_factory(Project,
                                      MaitreOeuvre,
                                      fields='__all__',
                                      can_delete=True,
                                      extra=1)
     context['formset_2'] = FormSet2(instance=current_object)
     if self.request.user == current_object.owner or self.request.user in current_object.editors.all(
     ):
         context['editable'] = True
     return context
Beispiel #9
0
def floodInstances(request):
	events=[]
	if request.method == 'GET':
		date=request.GET['date']
		events=getEvents(date)
	content=GeoJSONSerializer().serialize(events)
	return HttpResponse(content,content_type="application/json")
Beispiel #10
0
def postAlertPolygon(request):
    geofenceForm = GeofenceForm(request.POST)
    geofenceForm.data = geofenceForm.data.copy()

    # Create valid attributes for user and geom fields
    try:
        geofenceForm.data['user'] = request.user.id
        geofenceForm.data['geom'] = GEOSGeometry(geofenceForm.data['geom'])
    except (ValueError):
        messages.error(
            request, '<strong>' + _('Error') + '</strong><br>' +
            _('Invalid geometry data.'))

    if geofenceForm.is_valid():
        # Save new model object, send success message to the user
        polygon = geofenceForm.save()
        # messages.success(request, _('You will now receive alerts for the area traced.'))
        return JsonResponse({
            'success':
            True,
            'polygon':
            GeoJSONSerializer().serialize([
                polygon,
            ])
        })
    else:
        return JsonResponse({'success': False})
Beispiel #11
0
 def get(self, request, *args, **kwargs):
     """Returns GeoJSON for all the map's markers"""
     _map = Map.objects.get(id=kwargs['idx'])
     data = GeoJSONSerializer().serialize(Marker.objects.filter(map=_map),
                                          geometry_field='point',
                                          use_natural_keys=True,
                                          with_modelname=False)
     return HttpResponse(data, content_type='application/json')
Beispiel #12
0
def zonas(request):
    zonas = Zona.objects.all()
    contenidos = []
    for z in zonas:
        contenidos.append({'nombre': z.nombre,'uso': z.uso, 'planta': z.planta.nombre, 'riesgo': z.riesgo, 'geom': z.zona, 'riesgo': z.nivel_riesgo,})

    data = GeoJSONSerializer().serialize(contenidos, use_natural_keys=False, with_modelname=False)
    return HttpResponse(data)
Beispiel #13
0
def centro2(request, planta, centro):
    #tcn = Trabajador.objects.all()
    tcn = Trabajador.objects.filter(centroNegocios__codigo = centro)
    #s = FlatJsonSerializer()
    contenidos = []
    punto=None
    for i, tr in enumerate(tcn):
        if tr.gps_id:
#        t = Trabajador.objects.get(id=trabajador) #Trabajadores con el id solicitado
            dev = Devices.objects.get(id=tr.gps_id) #Dispositivo correspondiente al trabajador
            punto = Positions.objects.get(id = dev.positionid)
        auxiliar=Alertatrabajador()
        #auxiliar.geom='SRID=4326;POINT()'
        #auxiliar.lat=punto.lat
        #auxiliar.lon=punto.lon
        #auxiliar.address=punto.address
        #auxiliar.fixtime=punto.fixtime
        auxiliar.nombre=tr.primer_nombre+" "+tr.apellidop
        auxiliar.id=tr.id
        auxiliar.i=i
        if(tr.tipo_contacto):
            auxiliar.tipo_contacto=tr.tipo_contacto
        else:
            auxiliar.tipo_contacto="Sin Información"
        if(tr.emergencia):
            auxiliar.nombre_emergencia=tr.emergencia.nombre
            auxiliar.nro_emergencia=tr.emergencia.fono
        else:
            auxiliar.nombre_emergencia="Sin Información"
            auxiliar.nro_emergencia="Sin Información"
        if(tr.foto):
            auxiliar.foto=tr.foto.url
        else:
            auxiliar.foto="/media/avatar/defecto.png"
        #auxiliar.foto=tr.foto.url
        auxiliar.geom=punto.geom
        auxiliar.apellidop=tr.apellidop
        #auxiliar.apellidom=tr.apellidom
        #auxiliar.fecha_nac=tr.fecha_nac
        #auxiliar.estudios=t.estudios
        #auxiliar.rut=tr.rut
        auxiliar.nivel_riesgo=tr.nivel_riesgo
        if(tr.fono):
            auxiliar.fono=tr.fono
        else:
            auxiliar.fono="Sin Información"
        if(tr.cargo):
            auxiliar.cargo=tr.cargo
        else:
            auxiliar.cargo="Sin Información"
        #auxiliar.direccion=tr.direccion
        #auxiliar.centroNegocios=t.centroNegocios
        #auxiliar.gps=t.gps
        contenidos.append(auxiliar)
    #data = s.serialize(contenidos)
    data = GeoJSONSerializer().serialize(contenidos, use_natural_keys=False, with_modelname=False)

    return HttpResponse(data)#, content_type='application/json')
Beispiel #14
0
def paises(request):
    paises = world.objects.all()
    #    contenidos = []

    data = GeoJSONSerializer().serialize(paises,
                                         use_natural_keys=True,
                                         with_modelname=False)

    return HttpResponse(data)
Beispiel #15
0
def areasVerdes(request):
    areasVerdes = areaVerde.objects.all()
    #    contenidos = []

    data = GeoJSONSerializer().serialize(areasVerdes,
                                         use_natural_keys=True,
                                         with_modelname=False)

    return HttpResponse(data)
Beispiel #16
0
def experience_(request, id):
    experiences = Experience.objects.get(id=id)
    geojson = GeoJSONSerializer().serialize(experiences,
                                            geometry_field=('centroid'),
                                            properties=('title',
                                                        'description_short',
                                                        'status', 'statusfr'))
    return render(request, 'consulter_.html', {
        'experiences': experiences,
        'geojson': geojson,
    })
Beispiel #17
0
def track_tour(request, touralias):
    tour = get_object_or_404(Tour, alias=touralias)
    track = tour.track
    data = {
        'type': 'Feature',
        'geometry': track,
        'properties': {
            'name': tour.name,
            'color': tour.color
        }
    }
    geo_json = {'type': 'FeatureCollection', 'features': [data]}
    json = GeoJSONSerializer().serialize(data)
    #return HttpResponse(json, content_type='application/json')
    return JsonResponse(geo_json)
def find_rocks(request):
    """
    Given a given lat/long pair, return the unit(s) surrounding it.
    """
    if request.is_ajax():
        lat = request.GET.get('lat', None)
        lon = request.GET.get('lon', None)

        if lat and lon:
            point = Point(float(lon), float(lat))
            units = Unit.objects.filter(geom__contains=point)
            geojson_data = GeoJSONSerializer().serialize(units,
                                                         use_natural_keys=True)

            return HttpResponse(geojson_data, mimetype='application/json')
    msg = "Bad request: not AJAX or no latlong pair present"
    return HttpResponseBadRequest(msg)
Beispiel #19
0
    def get(self, request):

        if os.path.isfile(
                os.path.join(settings.MEDIA_ROOT + 'regions.geojson')) and int(
                    self.get_last_modification_time()) < self.get_file_time():
            geojson = self.file_get_contents(settings.MEDIA_ROOT +
                                             'regions.geojson')
        else:
            # create file/folder if it does not exist
            geojson = GeoJSONSerializer().serialize(Region.objects.all(),
                                                    geometry_field='geom',
                                                    properties=('id', 'name'),
                                                    precision=4)
            f = open(settings.MEDIA_ROOT + 'regions.geojson', 'w')
            f.write(geojson)
            f.close()
        return HttpResponse(geojson)
Beispiel #20
0
    def render_to_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        serializer = GeoJSONSerializer()
        response = self.response_class(**response_kwargs)
        options = dict(properties=self.properties,
                       precision=self.precision,
                       simplify=self.simplify,
                       srid=self.srid,
                       geometry_field=self.geometry_field,
                       force2d=self.force2d)
        serializer.serialize(self.get_queryset(),
                             stream=response,
                             ensure_ascii=False,
                             **options)

        return response
Beispiel #21
0
def consulter(request):
    experiences = Experience.objects.all()
    f = ExperienceFilter(request.GET, queryset=Experience.objects.all())
    search = False
    if len(request.GET) > 0:
        search = True
    geojson = GeoJSONSerializer().serialize(f.qs,
                                            geometry_field=('centroid'),
                                            properties=('title',
                                                        'description_short',
                                                        'status', 'statusfr'))
    return render(
        request, 'consulter.html', {
            'filter': f,
            'experiences': experiences,
            'geojson': geojson,
            'search': search,
        })
Beispiel #22
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')
Beispiel #23
0
 def get(self, request, region_id):
     region = Region.objects.get(pk=region_id)
     if os.path.isfile(
             os.path.join(settings.MEDIA_ROOT + 'dwd_stations.geojson')):
         geojson = self.file_get_contents(settings.MEDIA_ROOT +
                                          'dwd_stations.geojson')
     else:
         # create file/folder if it does not exist
         geojson = GeoJSONSerializer().serialize(
             DWDStation.objects.filter(geom__intersects=region.geom),
             geometry_field='geom',
             properties=tuple(
                 [f.name for f in DWDStation._meta.get_fields()]),
             precision=4)
         geojson = json.loads(geojson)
         del geojson['crs']
         geojson = json.dumps(geojson)
         f = open(settings.MEDIA_ROOT + 'dwd_stations.geojson', 'w')
         f.write(geojson)
         f.close()
     return HttpResponse(geojson)
Beispiel #24
0
def planta(request, planta):
#Posiciones registradas dentro de una determinada planta
    pl = Planta.objects.get(nombre = planta)
#    s = FlatJsonSerializer()
    contenidos = []

    for d in Devices.objects.all():
        if(Positions.objects.filter(id = d.positionid).exists()):
            p = Positions.objects.get(id = d.positionid)
            if(pl.geom.contains(p.geom)):
                contenidos.append(p)


#    for p in puntos:
#        if(pl.geom.contains(p.geom)):
#            contenidos.append(p)

#    data = serializers.serialize('json', contenidos)
    data = GeoJSONSerializer().serialize(contenidos, use_natural_keys=True, with_modelname=False)

    return HttpResponse(data)#, content_type='application/json')
Beispiel #25
0
def postPoint(request, Form):
    """Submit a user point submission to the database. Normalize geometry and activate push notifications."""
    form = Form(request.POST)
    form.data = form.data.copy()

    # Convert coords to valid geometry
    try:
        form.data['geom'] = normalizeGeometry(form.data['geom'])
    except (ValueError):
        # TODO provide error message to user here
        JsonResponse({'success': False})
        # messages.error(request, '<strong>' + _('Error') + '</strong><br>' + _('No point was selected for this type of report.'))

    # Validate and submit to db
    if form.is_valid():
        point = form.save()
        # Errors with push notifications should not affect reporting
        if not settings.DEBUG:
            try:
                pushNotification.pushNotification(point)
            except:
                pass

        return JsonResponse({
            'success': True,
            'point': GeoJSONSerializer().serialize([
                point,
            ]),
            'point_type': point.p_type,
            'form_html': render_crispy_form(Form())
        })
    else:
        logger.debug("Form not valid")

    # Else: error occurred
    form.data['geom'] = form.data['geom'].json
    form_html = render_crispy_form(form)
    return JsonResponse({'success': False, 'form_html': form_html})
Beispiel #26
0
def json_markers():
    return GeoJSONSerializer().serialize(Marker.objects.all(), use_natural_keys=True, with_modelname=False)
Beispiel #27
0
def json_polygons():
    return GeoJSONSerializer().serialize(Polygon.objects.all(), use_natural_keys=True, with_modelname=False)
Beispiel #28
0
def index(request):

    geo_json_string = GeoJSONSerializer().serialize(Location.objects.all(),
                                                    use_natural_keys=True,
                                                    with_modelname=False)

    querySet = [("M'bera Refugee Camp", 'MR'),
                ("Burkina Faso Refugee Camp", 'BF'),
                ("Niger Refugee Camp", 'NE'), ("Niger Refugee Camp", 'NE'),
                ("Malawi Refugee Camp", 'MW'), ("Kenya Refugee Camp", 'KY'),
                ("Ethiopia Refugee Camp", 'ET'), ("Syria Refugee Camp", 'SY'),
                ("Jordan Refugee Camp", 'JO'), ("Iraq Refugee Camp", 'IQ'),
                ("Bangladesh Refugee Camp", 'BD'),
                ("Sudan Refugee Camp", 'SD'), ("Turkey Refugee Camp", 'TR'),
                ("West Nile Refugee Camp", 'WN')]

    links = []
    for query, iso2 in querySet:

        all_articles = newsapi.get_everything(
            q=query,
            from_param=datetime.datetime.now().date() - timedelta(days=29),
            to=datetime.datetime.now().date(),
            language='en',
            sort_by='relevancy',
            page=1)
        countryToList = {}

        if (all_articles['totalResults'] is 0):
            all_articles = newsapi.get_everything(
                q='Refugee Camps',
                from_param=datetime.datetime.now().date() - timedelta(days=29),
                to=datetime.datetime.now().date(),
                language='en',
                sort_by='relevancy',
                page=1)
        subList = []
        for article in all_articles['articles']:
            info = {
                'url': (article['url']),
                'headline':
                (str(article['title']).replace(u"\u2018",
                                               "'").replace(u"\u2019", "'"))
            }
            subList.append(info)

        countryToList[iso2] = subList
        links.append(countryToList)

    linksJson = json.dumps(links)

    print(linksJson)

    #end of articles - start of regional stats queries

    regionsQuery = Population.objects.values_list(
        "region", flat=True).order_by("region").distinct()
    regionsList = list(regionsQuery)

    regionJSONs = []

    for region in regionsList:
        regionsPop = {}
        regionsPop['region'] = region
        regionsPop['population'] = (Population.objects.filter(
            region=region).aggregate(Sum('refugeePop')))['refugeePop__sum']
        regionJSONs.append(regionsPop)

    regionsPop = json.dumps(regionJSONs)

    subregionsQuery = Population.objects.values_list(
        "subRegion", flat=True).order_by("subRegion").distinct()
    subregionsList = list(subregionsQuery)

    subregionsJSONs = []

    for subregion in subregionsList:
        subregionsPop = {}
        subregionsPop['subregion'] = subregion
        subregionsPop['population'] = (Population.objects.filter(
            subRegion=subregion).aggregate(
                Sum('refugeePop')))['refugeePop__sum']
        subregionsJSONs.append(subregionsPop)

    subregionsPop = json.dumps(subregionsJSONs)

    countriesQuery = Population.objects.values_list(
        "origin", flat=True).order_by("refugeePop").distinct()
    countriesList = list(countriesQuery)
    countriesList = countriesList[-9:]
    print(countriesList)
    countriesJSONs = []

    for country in countriesList:
        countriesPop = {}
        countriesPop['country'] = country
        countriesPop['population'] = (Population.objects.filter(
            origin=country).aggregate(Sum('refugeePop')))['refugeePop__sum']
        countriesJSONs.append(countriesPop)

    countriesPop = json.dumps(countriesJSONs)

    # instantiate PyUnsplash object

    # pyunsplash logger defaults to level logging.ERROR
    # If you need to change that, use getLogger/setLevel
    # on the module logger, like this:

    # Start with the generic collection, maximize number of items
    # note: this will run until all photos of all collections have
    #       been visited, unless a connection error occurs.
    #       Typically the API hourly limit gets hit during this

    user = flickr_api.Person.findByUserName('MedGlobal')
    photos = user.getPhotos()

    images = []
    i = 0
    for photo in photos:
        i += 1
        linkAndAuthor = {'link': photo.getPhotoFile(), 'title': photo.title}
        images.append(linkAndAuthor)
        if i == 20:
            break

    images = json.dumps(images)

    return render(
        request, "maps/index.html", {
            'geo_json_string': geo_json_string,
            'links': linksJson,
            'regions': regionsPop,
            'subregions': subregionsPop,
            'countries': countriesPop,
            'images': images,
            'MAPBOX_KEY': MAPBOX_KEY
        })
Beispiel #29
0
def get_map(request):
    if request.method == 'POST':
        if request.is_ajax():
            ip = json.loads(request.POST['data'])
            ##print ip
            ##Get Class Name##
            cls = klass[ip['kclass']]

            ##Feature_list
            ftr = features[ip['feature'][0]]

            ##color_range
            frm, to = Color(colors[ip['feature'][0]][0]), Color(
                colors[ip['feature'][0]][1])

            ##five ranges
            color_range = frm.range_to(to, 6)

            wt = None
            ##get the weights
            if not ip['weight']:
                wt = weights[ip['feature'][0]]
            else:
                wt = ip['weight'].values()
                wt = {i[0]: float(i[1]) for i in wt}

            ##Filter Based On Location
            loc = ip['location']

            val_fields = ['geom']
            #val_fields.extend(loc.keys())

            if ip['kclass'] == 'district':
                val_fields += ['distname']
            elif ip['kclass'] == 'taluka':
                val_fields += ['distname']
                val_fields += ['block_name']

            ##Get Field Names
            fl_val, fl_name = zip(*ftr)

            val_fields += list(fl_val)

            ##Creating QueryDict
            query_dict = {location[k]: v for k, v in loc.iteritems()}

            ##filter based on location
            query = cls.objects.all()

            for k, v in query_dict.iteritems():
                query = query.filter(**{k: v})

            query = query.values(*val_fields)
            result = query

            result = GeoJSONSerializer().serialize(result)

            dict_json = json.loads(result)
            #print dict_json
            #remove crs field
            dict_json.pop('crs', None)

            ind_lst = []
            dist_no_geom = []
            ## iterate over the features
            for feature_dict in dict_json['features']:

                ## pop out the properties and store it in props
                props = feature_dict.pop('properties', None)

                #print feature_dict

                ## remove location info and store in variables
                distname = ''
                talukaname = ''
                if props.has_key('distname'):
                    distname = props.pop('distname', None)

                if props.has_key('block_name'):
                    talukaname = props.pop('block_name', None)

                ##remaining pairs are the fields
                index = 0

                for k in props:
                    index += round(props[k] * wt[k], 2)
                ind_lst += [index]

                temp = dict()
                if not feature_dict['geometry']:
                    if distname:
                        temp = {"district": distname, "index": round(index, 2)}

                    if talukaname:
                        temp = {
                            "district": distname,
                            "taluka": talukaname,
                            "index": round(index, 2)
                        }

                    #print temp
                    dist_no_geom += [temp]

                ## add the index
                feature_dict['properties'] = {}
                feature_dict['properties']['index'] = round(index, 2)
                ## add the locations
                if distname:
                    feature_dict['properties']['distname'] = distname
                if talukaname:
                    feature_dict['properties']['taluka'] = talukaname

            min_v = max(0, floor(min(ind_lst)) - 1)
            max_v = floor(max(ind_lst)) + 1
            rg = round(max_v - min_v, 2)
            grade = [
                round(min_v + (rg * (float(i) / 100)))
                for i in range(0, 120, 20)
            ]
            #print min_v,max_v
            #print grade
            color_range = [str(i) for i in color_range]
            #print color_range
            data = {
                'geographic_data': dict_json,
                'color': color_range,
                'grade': grade,
                'no_geom': dist_no_geom,
            }

            result = json.dumps(data)

        return HttpResponse(result)
    else:
        raise Http404("Access Denied!")
Beispiel #30
0
def find_facilities(request):
    """
	Give a lat/lon pair, return the unit(s) surround it.
	"""
    #example of a get request: http://127.0.0.1:8000/find/?lat=18.57&lon=-72.293&buffer=1000

    #if request.is_ajax():
    lat = request.GET.get('lat', None)
    lon = request.GET.get('lon', None)

    #need a buffer distance...
    buffer = request.GET.get('buffer', None)

    #make default buffer value 1000 if it is not specified
    if not buffer:
        buffer = 1000

#else:
#msg = "Bad request: no AJAX present"
#return HttpResponseBadRequest(msg)

    #point = Point(float(lon), float(lat))
    lon = float(lon)
    lat = float(lat)
    point2 = Point(lon, lat)

    print(point2)
    print(buffer)

    #test_pnt = Point(-104.93, 39.73)
    """
	Why distance_lt instead of dwithin?
	http://stackoverflow.com/questions/2235043/geodjango-difference-between-dwithin-and-distance-lt
	"""
    '''
	originally I tried .get() , but that returned a MultipleObjectsReturned error
	so I changed it to .filter()
	If there will be more than one result, you need .filter()
	'''

    #depreciated (doing buffer queries on the Location table instead of Location_w_efforts
    #facilities = Location_w_efforts.objects.filter(geom__distance_lt=(point2, D(m=buffer)))

    #testing query not using Location_w_efforts table
    #probably best to Location_w_efforts as a temporary table to just store
    #results of buffer, then I could serialize it with GeoJSONSerializer, and erase the table afterwards
    locations_only = Location.objects.filter(geom__distance_lt=(point2,
                                                                D(m=buffer)))
    print('printing locations_only')
    print(locations_only)

    #https://docs.djangoproject.com/en/1.7/topics/db/examples/one_to_one/
    #need to find all effort instances that have the locations in facilities

    efforts_matching_locations_only = EffortInstance.objects.filter(
        location=locations_only)

    print('printing efforts_matching_locations_only')
    #print(efforts_matching_locations_only)

    #add results of buffer (effort instance info, location geom, service provider name) to Location_w_efforts_temp table

    Location_w_efforts_temp.objects.all().delete()

    nearby = 'nearby'
    for i in efforts_matching_locations_only:

        add_to_Location_w_efforts_tempObj(i, nearby)
    '''
	
		print('printing object')
		print(item.service_provider.service_provider_id)
		
		Location_w_efforts_tempObj = Location_w_efforts_temp()
		
		Location_w_efforts_tempObj.date_start = item.date_start
		Location_w_efforts_tempObj.date_end = item.date_end
		Location_w_efforts_tempObj.latitude = item.location.latitude
		Location_w_efforts_tempObj.longitude = item.location.longitude
		Location_w_efforts_tempObj.id = item.effort_instance_id
		Location_w_efforts_tempObj.service_provider = item.service_provider
		Location_w_efforts_tempObj.provider_name = item.service_provider.provider_name
		
		Location_w_efforts_tempObj.save()
	'''

    print('done filling table')

    #depreciated
    #geojson_data = GeoJSONSerializer().serialize(facilities, use_natural_keys=True)

    geojson_data = GeoJSONSerializer().serialize(
        Location_w_efforts_temp.objects.all(), use_natural_keys=True)

    return HttpResponse(geojson_data, content_type='application/json')