Example #1
0
def serialize(features, properties=None):
    if not properties:
        properties = ['title', 'description', 'owner_id']
    djf = Django.Django(geodjango="geometry", properties=properties)
    geoj = GeoJSON.GeoJSON()
    jsonstring = geoj.encode(djf.decode(features))
    return jsonstring
Example #2
0
def geojson(request):
    try:
        westlng = request.GET["westlng"]
        eastlng = request.GET["eastlng"]
        northlat = request.GET["northlat"]
        southlat = request.GET["southlat"]
    except KeyError:
        return json_response({})
    wkt = (
        "POLYGON(("
        "%(w)s %(s)s, "
        "%(w)s %(n)s, "
        "%(e)s %(n)s, "
        "%(e)s %(s)s, "
        "%(w)s %(s)s"
        "))" % {"w": westlng, "e": eastlng, "s": southlat, "n": northlat}
        )
    qs = Parcel.objects.filter(geom__intersects=wkt).prefetch_mapped()
    features = []
    serializer = UIParcelSerializer()
    for parcel in qs:
        feature = Feature(parcel.id)
        feature.geometry = {
            "type": parcel.geom.geom_type,
            "coordinates": parcel.geom.coords,
            }
        feature.properties = serializer.one(parcel)
        features.append(feature)

    output = GeoJSON.GeoJSON().encode(features, to_string=False)
    return json_response(output)
Example #3
0
def wkt_to_geojson(wktStr):
    """Return GeoJSON from a WKT string."""
    # Create instances of vectorfeatures WKT/GeoJSON Classes
    inWKT = WKT.WKT()
    outGeoJSON = GeoJSON.GeoJSON()
    # Decode WKT to vectorformats features, and re-encode as GeoJSON
    return outGeoJSON.encode(inWKT.decode(wktStr), to_string=True)
Example #4
0
def source_points(request):
    from vectorformats.Formats import Django, GeoJSON
    source_points = Source.objects.exclude(point=None)
    djf = Django.Django(geodjango="point",
                        properties=['name', 'id', 'absolute_url'])
    geoj = GeoJSON.GeoJSON()
    s = geoj.encode(djf.decode(source_points))
    return HttpResponse(s, content_type="application/json")
Example #5
0
def labels(request, id=0):
    from vectorformats.Formats import Django, GeoJSON
    qs = Label.objects.filter(track=id)
    djf = Django.Django(geodjango="geom", properties=['name', 'desc'])
    geoj = GeoJSON.GeoJSON()
    s = geoj.encode(djf.decode(qs))
    response = HttpResponse(s, mimetype="application/json")
    return response
Example #6
0
def puntjson(request):
    puntos = PuntosInteres.objects.all()
    djf = Django.Django(geodjango="geometry",
                        properties=['name', 'descripcion'])
    geoj = GeoJSON.GeoJSON()
    string = geoj.encode(djf.decode(puntos))
    data = serializers.serialize('json', puntos)
    print string
    return HttpResponse(string, mimetype='application/json')
Example #7
0
def puntosjson(request):
    puntos = PuntosInteres.objects.all()
    djf = Django.Django(geodjango="geometry",
                        properties=['name', 'descripcion'])
    geoj = GeoJSON.GeoJSON()
    string = geoj.encode(djf.decode(puntos))
    print string
    return render_to_response('world/leatflet.html', [string],
                              context_instance=RequestContext(request))
Example #8
0
 def get(self, request, *args, **kwargs):
     """
     TODO: improve readability and cleanup
     """
     node = Node.objects.published().accessible_to(request.user)
     dj = Django.Django(geodjango="coords", properties=['name', 'description'])
     geojson = GeoJSON.GeoJSON()
     string = geojson.encode(dj.decode(node))  
     
     return Response(json.loads(string))
Example #9
0
def get_hospitals(request):
    qs = Facility.objects.exclude(the_geom=None)
    djf = Django.Django(geodjango="the_geom",
                        properties=['id', 'name', 'description', 'manager_id',
                                    'address', 'phone', 'email',
                                    'facility_type_id'])
    geoj = GeoJSON.GeoJSON()
    geojson_output = geoj.encode(djf.decode(qs))
    response = HttpResponse(mimetype="application/json")
    response.write(geojson_output)

    return response
Example #10
0
 def render_to_response(self, context, **response_kwargs):
     """
     Return as a nice geojson layer
     """
     village_list = context['village_list']
     properties_wanted = [
         'name', 'population', 'provinsi', 'kecamatan', 'desa', 'quartile',
         'dataseries'
     ]
     djf = Django.Django(geodjango="geom", properties=properties_wanted)
     encoder = GeoJSON.GeoJSON()
     geojson_str = encoder.encode(djf.decode(village_list))
     return HttpResponse(geojson_str, content_type="application/json")
Example #11
0
    def get(self, *args, **kwargs):
        """
        Returns data in GeoJSON format ready to be consumed by a mapping system
        """
        queryset = Venue.objects.filter(city__icontains="toronto")

        django_formatter = Django.Django(
            geodjango="coordinates",
            properties=['name', 'city', 'state'])
        geojson_formatter = GeoJSON.GeoJSON()
        data = json.loads(geojson_formatter.encode(django_formatter.decode(queryset)))

        return Response(data)
Example #12
0
def get_geojson(request):
    defzwiedzanie = request.GET['zwiedzanie']
    deftype = request.GET['typ']

    forty_ob = Forty.objects.filter(typ__contains=deftype,
                                    zwiedzanie__contains=defzwiedzanie)

    djf = Django.Django(
        geodjango='mpoly',
        properties=['nazwa', 'adres', 'typ', 'otwarty', 'zwiedzanie'])
    geoj = GeoJSON.GeoJSON()
    gjson = geoj.encode(djf.decode(forty_ob))

    return HttpResponse(gjson)
Example #13
0
def poligonos(request):
    puntos = Poligonos.objects.all()
    djf = Django.Django(geodjango="geometry",
                        properties=['name', 'descripcion'])
    geoj = GeoJSON.GeoJSON()
    data = geoj.encode(djf.decode(puntos))
    pnt = Point(-65.7833, -28.4667, srid=4326)
    pnt.transform(4269)
    lon, lat = pnt.coords
    pnti = Point(-65.7833, -28.4667, srid=4326)
    pnti.transform(900913)
    loni, lati = pnti.coords
    #data = serializers.serialize('json',puntos)
    #return HttpResponse(data, mimetype='application/json')
    return render_to_response('world/poligonos.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #14
0
def get_hospitals(request):
    qs = Facility.objects.all()

    # TODO: Only for test! must be rewritten ASAP
    search = request.GET.get("search", None)
    if search:
        pathologies = Pathology.objects.filter(name__contains=search)
        qs = set()
        for p in pathologies:
            qs.update(p.facility_set.all())

    djf = Django.Django(geodjango="the_geom", properties=["id", "name"])
    geoj = GeoJSON.GeoJSON()
    geojson_output = geoj.encode(djf.decode(qs))
    response = HttpResponse(mimetype="application/json")
    response.write(geojson_output)

    return response
Example #15
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")
    def handle(self, *args, **options):
        """
        Exports neighborhood to data directory, simplifying the polygons in the process.
        Simplify: https://docs.djangoproject.com/en/1.4/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry.simplify
        """
        data_path = 'portal/static/js'
        neighborhoods = Neighborhood.objects.annotate(
            num_schools=Count('location')).filter()

        for n in neighborhoods:
            n.center = n.get_center()

            # Simplify our boundaries so they take up less space
            newBoundary = n.boundary.simplify(settings.SIMPLIFY_EPSILON, True)
            if newBoundary.geom_type == 'MultiPolygon':
                n.boundary = newBoundary
            elif newBoundary.geom_type == 'Polygon':
                n.boundary = MultiPolygon(newBoundary)
            else:
                raise TypeError('Invalid type ' + n.boundary.geom_type +
                                ' encountered')

        geoj = GeoJSON.GeoJSON()
        djf = Django.Django(
            geodjango='boundary',
            properties=['primary_name', 'pk', 'center', 'num_schools'])

        json = geoj.encode(djf.decode(neighborhoods))

        output = open(data_path + '/neighborhoods.json', 'w')
        output.write(json)
        output.close()

        topo_path = data_path + '/neighborhoods-topo.json'
        geo_path = data_path + '/neighborhoods.json'
        subprocess.check_call(['topojson', '-p', '-o', topo_path, geo_path])

        sys.stdout.write('Succesfully exported %s neighborhoods\n' %
                         len(neighborhoods))
Example #17
0
    def get(self, request, *args, **kwargs):
        """
        Get nodes of specified existing and published layer
        or otherwise return 404
        Outputs nodes in geojson format
        TODO: improve readability and cleanup

        """
        # ensure exists
        try:
            # retrieve slug value from instance attribute kwargs, which is a dictionary
            slug_value = self.kwargs.get('slug', None)
            # get node, ensure is published
            layer = Layer.objects.get(slug=slug_value)
        except Exception:
            raise Http404(_('Layer not found'))
        node = layer.node_set.all()
        dj = Django.Django(geodjango="coords",
                           properties=['name', 'description'])
        geojson = GeoJSON.GeoJSON()
        string = geojson.encode(dj.decode(node))

        return Response(json.loads(string))
Example #18
0
def djangoToExportFormat(request,
                         filter_object,
                         properties_list=None,
                         geom_col="geom",
                         format="geojson"):
    """Convert a GeoDjango QuerySet to a GeoJSON Object"""

    #Workaround for mutable default value
    if properties_list is None:
        properties_list = []
        #Return dictionary of key value pairs
        filter_dict = filter_object[0].__dict__
        #Remove bunk fields
        for d in filter_dict:
            if isinstance(filter_dict[d], django.db.models.base.ModelState):
                pass
            # Convert decimal to float
            elif isinstance(filter_dict[d], Decimal):
                for obj in filter_object:
                    setattr(obj, d, float(obj.__dict__[d]))
                properties_list.append(d)
            # Convert date to string
            elif isinstance(filter_dict[d], date):
                for obj in filter_object:
                    setattr(obj, d, str(obj.__dict__[d]))
                properties_list.append(d)
            # Convert time to string
            elif isinstance(filter_dict[d], time):
                for obj in filter_object:
                    setattr(obj, d, str(obj.__dict__[d]))
                properties_list.append(d)
            else:
                properties_list.append(d)

        properties_list.remove(geom_col)

    queryset = filter_object
    djf = Django.Django(geodjango=geom_col, properties=properties_list)
    decode_djf = djf.decode(queryset)
    if format.lower() == 'geojson':
        geoj = GeoJSON.GeoJSON()
        # Pretty Print using JSON dumps method. Note requires setting
        # vectorformats encode method to_string param to False.
        geom_out = dumps(geoj.encode(decode_djf, to_string=False),
                         indent=4,
                         separators=(',', ': '))
        response = HttpResponse(geom_out, content_type="text/plain")
    elif format.lower() == 'kml':
        # title property can be passed as a keyword arg.
        # See vectorformats kml.py
        kml = KML.KML(title_property='name')
        geom_out = kml.encode(decode_djf)
        response = HttpResponse(
            geom_out, content_type="application/vnd.google-earth.kml+xml")
        response['Content-Disposition'] = 'attachment; filename="kml_out.kml"'
    elif format.lower() == 'shp':
        # convert to GeoJSON, then Use Fiona to Create a Shapefile.
        geoj = GeoJSON.GeoJSON()
        geoJSON = dumps(geoj.encode(decode_djf, to_string=False),
                        indent=4,
                        separators=(',', ': '))

        # Hard source properties for the destination shapefile.
        # These will be passed to Fiona.
        shp_driver = 'ESRI Shapefile'
        shp_crs = {
            'no_defs': True,
            'ellps': 'WGS84',
            'datum': 'WGS84',
            'proj': 'longlat'
        }
        shp_schema = {
            'geometry': decode_djf[0].geometry['type'],
            'properties': {
                'addDate': 'str',
                'collectDate': 'str',
                'collectionMethod': 'str',
                'comment': 'str',
                'featurePurpose': 'str',
                'group': 'str',
                'name': 'str',
                'updateDate': 'str'
            }
        }

        upload_dir = make_temp_dir()
        zipdir = os.path.join(upload_dir, decode_djf[0].properties['group'])

        with fiona.open(zipdir,
                        'w',
                        driver=shp_driver,
                        crs=shp_crs,
                        schema=shp_schema) as dest_shp:
            for feature in decode_djf:
                out_feature = {'geometry': {}, 'properties': {}}
                for property in shp_schema['properties']:
                    out_feature['properties'][property] = feature[
                        'properties'][property]
                out_feature['geometry'] = feature['geometry']
                dest_shp.write(out_feature)

        # Create the zip archive
        zip = make_zip_archive(zipdir)
        shp_zip = open(zip.filename)
        response = HttpResponse(FileWrapper(shp_zip),
                                content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=shp_out.zip'
        response['Content-Length'] = os.path.getsize(zip.filename)

    else:
        raise ValueError
    return response
Example #19
0
def _convert_geodjango_to_json(queryset, properties):
    djf = Django.Django(geodjango='geometry', properties=properties)
    geoj = GeoJSON.GeoJSON()
    return geoj.encode(djf.decode(queryset))