示例#1
0
    def decode(self, query_set, generator=False):
        results = []
        for res in query_set:
            feature = Feature(res.pk)

            if self.pickled_geometry:
                feature.geometry = pickle.loads(res.geometry)

            elif self.geodjango:
                geometry = None
                geom = getattr(res, self.geodjango)
                if geom:
                    geometry = {}
                    geometry['type'] = geom.geom_type
                    geometry['coordinates'] = geom.coords
                feature.geometry = geometry

            if self.pickled_properties:
                props = getattr(res, self.pickled_properties)
                feature.properties = pickle.loads(props.encode("utf-8"))

            if self.properties:
                for p in self.properties:
                    feature.properties[p] = getattr(res, p)
            results.append(feature)
        return results
示例#2
0
    def decode(self, query_set, generator = False):
        results = []
        for res in query_set:
            feature = Feature(res.pk)
            
            if self.pickled_geometry:
                feature.geometry = pickle.loads(res.geometry)
            
            elif self.geodjango:
                geometry = None
                geom = getattr(res, self.geodjango)
                if geom:
                    geometry = {}
                    geometry['type'] = geom.geom_type
                    geometry['coordinates'] = geom.coords
                feature.geometry = geometry

            if self.pickled_properties:
                props = getattr(res, self.pickled_properties) 
                feature.properties = pickle.loads(props.encode("utf-8"))
            
            if self.properties:   
                for p in self.properties:
                    feature.properties[p] = getattr(res, p)
            results.append(feature) 
        return results    
示例#3
0
    def entry_to_feature(self, placemark_dom):
        feature = Feature()
        points = placemark_dom.getElementsByTagName("Point")
        lines = placemark_dom.getElementsByTagName("LineString")
        polys = placemark_dom.getElementsByTagName("Polygon")
        if len(points):
            coords = points[0].getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip().split(",")
            feature.geometry = {"type": "Point", "coordinates": map(float, coords)}
        elif len(lines):
            coordstring = lines[0].getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip()
            coords = coordstring.split(" ")
            coords = map(lambda x: x.split(","), coords)
            feature.geometry = {"type": "LineString", "coordinates": coords}
        elif len(polys):
            rings = []
            poly = polys[0]
            outer = poly.getElementsByTagName("outerBoundaryIs")[0]
            outer_coordstring = outer.getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip()
            outer_coords = outer_coordstring.split(" ")
            outer_coords = map(lambda x: map(float, x.split(",")), outer_coords)
            rings.append(outer_coords)
            inners = poly.getElementsByTagName("innerBoundaryIs")
            for inner in inners:
                inner_coords = inner.getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip().split(" ")
                inner_coords = map(lambda x: map(float, x.split(",")), inner_coords)
                rings.append(inner_coords)

            feature.geometry = {"type": "Polygon", "coordinates": rings}

        else:
            raise Exception(
                "KML parser only understands points and lines, and polys. You seem to be missing something."
            )
        nodeList = placemark_dom.childNodes
        if len(placemark_dom.getElementsByTagName("Metadata")):
            nodeList += placemark_dom.getElementsByTagName("Metadata")[0].childNodes
        for node in nodeList:
            try:
                attr_name = node.tagName.split(":")[-1]
                value = node.firstChild.nodeValue
                if node.tagName not in ["Point", "LineString", "Polygon", "name", "Metadata"] and not value.startswith(
                    "Properties:"
                ):
                    feature.properties[attr_name] = value
            except:
                pass

            try:
                feature.properties["title"] = placemark_dom.getElementsByTagName("name")[0].firstChild.nodeValue
            except:
                pass

        return feature
    def decode(self, query_set, generator=False):
        results = []
        for res in query_set:
            feature = Feature(res.id)

            if self.pickled_geometry:
                feature.geometry = pickle.loads(res.geometry)

            elif self.geodjango:
                geom = getattr(res, self.geodjango)
                geometry = {}
                geometry["type"] = geom.geom_type
                geometry["coordinates"] = geom.coords
                feature.geometry = geometry

            if self.pickled_properties:
                props = getattr(res, self.pickled_properties)
                feature.properties = pickle.loads(props.encode("utf-8"))

            if self.properties:
                for p in self.properties:
                    feature.properties[p] = getattr(res, p)

            if self.style:
                feature.properties["style"] = self.style

            if self.relation_data:
                for method, models in self.relation_data.iteritems():
                    if method == "set_count":
                        for model in models:
                            try:
                                result = getattr(res, model + "_set")
                                count = getattr(result, "count")
                                feature.properties[model + "_" + method] = count()
                            except AttributeError, err:
                                feature.properties[model + "_" + method] = "AttributeError"
                    if method == "values_list":
                        for model in models:
                            try:
                                result = getattr(res, model)
                                all_list = list(result.values_list())
                                feature.properties[model + "_" + method] = all_list
                            except AttributeError, err:
                                feature.properties[model + "_" + method] = "AttributeError"
                    if method == "display":
                        for model in models:
                            try:
                                display = "get_%s_display" % (model)
                                result = getattr(res, display)
                                feature.properties[model + "_" + method] = result()
                            except AttributeError, err:
                                feature.properties[model + "_" + method] = "AttributeError"
示例#5
0
 def entry_to_feature(self, placemark_dom):
     feature = Feature()
     points = placemark_dom.getElementsByTagName("Point")
     lines = placemark_dom.getElementsByTagName("LineString")
     polys = placemark_dom.getElementsByTagName("Polygon")
     if len(points):
         coords = points[0].getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip().split(",")
         feature.geometry = {'type':'Point', 'coordinates':map(float,coords)}
     elif len(lines):
         coordstring = lines[0].getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip()
         coords = coordstring.split(" ")
         coords = map(lambda x: x.split(","), coords)
         feature.geometry = {'type':'LineString', 'coordinates':coords}
     elif len(polys):
         rings = []
         poly = polys[0]
         outer = poly.getElementsByTagName("outerBoundaryIs")[0]
         outer_coordstring = outer.getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip()
         outer_coords = outer_coordstring.split(" ")
         outer_coords = map(lambda x: map(float,x.split(",")), outer_coords)
         rings.append(outer_coords)
         inners = poly.getElementsByTagName("innerBoundaryIs")
         for inner in inners:
             inner_coords = inner.getElementsByTagName("coordinates")[0].firstChild.nodeValue.strip().split(" ")
             inner_coords = map(lambda x: map(float,x.split(",")), inner_coords)
             rings.append(inner_coords)
         
         feature.geometry = {'type':'Polygon', 'coordinates':rings}
         
     else:
         raise Exception("KML parser only understands points and lines, and polys. You seem to be missing something.") 
     nodeList = placemark_dom.childNodes
     if len(placemark_dom.getElementsByTagName("Metadata")):
         nodeList += placemark_dom.getElementsByTagName("Metadata")[0].childNodes
     for node in nodeList:
         try:
             attr_name = node.tagName.split(":")[-1]
             value = node.firstChild.nodeValue
             if node.tagName not in ['Point', 'LineString', 'Polygon', 'name', 'Metadata'] and not value.startswith("Properties:"):
                 feature.properties[attr_name] = value
         except:
             pass
         
         try:
             feature.properties['title'] = placemark_dom.getElementsByTagName("name")[0].firstChild.nodeValue
         except:
             pass
     
     return feature    
示例#6
0
    def entry_to_feature(self, entry_dom):
        id = 1
        try:
            id = entry_dom.getElementsByTagName("id")[0].firstChild.nodeValue
        except:
            id = 1
        feature = Feature(str(id))

        geometry = self.extract_entry_geometry(entry_dom)

        if not geometry: return None

        feature.geometry = geometry

        for node in entry_dom.childNodes:
            try:
                attr_name = node.tagName.split(":")[-1]
                if attr_name not in [
                        'point', 'line', 'polygon', 'id', 'where'
                ]:
                    try:
                        feature.properties[
                            attr_name] = node.firstChild.nodeValue
                    except:
                        pass
            except:
                pass

        return feature
示例#7
0
 def entry_to_feature(self, entry_dom):
     id = 1 
     try:
         id = entry_dom.getElementsByTagName("id")[0].firstChild.nodeValue
     except:
         id = 1
     feature = Feature(str(id))
     
     geometry = self.extract_entry_geometry(entry_dom)
     
     if not geometry: return None
     
     feature.geometry = geometry
     
     for node in entry_dom.childNodes:
         try:
             attr_name = node.tagName.split(":")[-1]
             if attr_name not in ['point', 'line', 'polygon', 'id', 'where']:
                 try:
                     feature.properties[attr_name] = node.firstChild.nodeValue
                 except:
                     pass
         except:
             pass
             
     return feature    
示例#8
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)
示例#9
0
 def _createFeature(self, feature_dict, id = None):
     """Private. Not designed to be used externally."""
     feature = Feature(id)
     if feature_dict.has_key('geometry'):
         feature.geometry = feature_dict['geometry']
     if feature_dict.has_key('properties'):
         feature.properties = feature_dict['properties']
     return feature 
示例#10
0
 def _createFeature(self, feature_dict, id=None):
     """Private. Not designed to be used externally."""
     feature = Feature(id)
     if feature_dict.has_key("geometry"):
         feature.geometry = feature_dict["geometry"]
     if feature_dict.has_key("properties"):
         feature.properties = feature_dict["properties"]
     return feature
示例#11
0
    def decode(self, query_set, generator=False):
        results = []
        for res in query_set:
            feature = Feature(res.id)
            if self.pickled_geometry:
                feature.geometry = pickle.loads(res.geometry)

            elif self.geodjango:
                geom = getattr(res, self.geodjango)
                geometry = {}
                geometry['type'] = geom.geom_type
                geometry['coordinates'] = geom.coords
                feature.geometry = geometry

            if self.pickled_properties:
                props = getattr(res, self.pickled_properties)
                feature.properties = pickle.loads(props.encode("utf-8"))

            if self.properties:
                for p in self.properties:
                    # This simple change allows us to span relationships between models:
                    # feature.properties[p] = getattr(res, p)
                    feature.properties[p] = reduce(getattr, p.split('__'), res)

            # An argument can be passed to access querysets (one to many relationships)
            # from each Feature returned, appending the querysets to the value's 'properties'
            if self.queries:
                for q in self.queries:
                    itemslist = []
                    for queryresult in q.getset(res):
                        item = {}
                        for k, v in queryresult.iteritems():
                            item[k] = v
                        itemslist.append(item)
                    feature.properties[q.queryparameters] = itemslist
            results.append(feature)
        return results
示例#12
0
    def decode(self, query_set, generator = False):
        results = []
        for res in query_set:
            feature = Feature(res.id)
            if self.pickled_geometry:
                feature.geometry = pickle.loads(res.geometry)

            elif self.geodjango:
                geom = getattr(res, self.geodjango)
                geometry = {}
                geometry['type'] = geom.geom_type
                geometry['coordinates'] = geom.coords
                feature.geometry = geometry

            if self.pickled_properties:
                props = getattr(res, self.pickled_properties)
                feature.properties = pickle.loads(props.encode("utf-8"))

            if self.properties:
                for p in self.properties:
                # This simple change allows us to span relationships between models:
                    # feature.properties[p] = getattr(res, p)
                    feature.properties[p] = reduce(getattr, p.split('__'), res)

            # An argument can be passed to access querysets (one to many relationships)
            # from each Feature returned, appending the querysets to the value's 'properties'
            if self.queries:
                for q in self.queries:
                    itemslist = []
                    for queryresult in q.getset(res):
                        item = {}
                        for k,v in queryresult.iteritems():
                            item[k] = v
                        itemslist.append(item)
                    feature.properties[q.queryparameters] = itemslist
            results.append(feature)
        return results
示例#13
0
    def freeze_features (self, features):
        result = []
        for ogrfeat in features:
            feat = Feature(ogrfeat.GetFID())

            geom = ogrfeat.GetGeometryRef()
            feat.geometry = OGR.freeze_geometry(geom)

            for n, defn in enumerate(self.fields):
                key = defn.GetName()
                if self.attribute_cols and not key.lower() in self.attribute_cols:
                    continue
                value = ogrfeat.GetField(n)
                if isinstance(value, str): value = unicode(value, "utf-8")
                feat.properties[key] = value 

            result.append(feat)
            ogrfeat.Destroy() 

        return result
示例#14
0
    def freeze_features(self, features):
        result = []
        for ogrfeat in features:
            feat = Feature(ogrfeat.GetFID())

            geom = ogrfeat.GetGeometryRef()
            feat.geometry = OGR.freeze_geometry(geom)

            for n, defn in enumerate(self.fields):
                key = defn.GetName()
                if self.attribute_cols and not key.lower(
                ) in self.attribute_cols:
                    continue
                value = ogrfeat.GetField(n)
                if isinstance(value, str): value = unicode(value, "utf-8")
                feat.properties[key] = value

            result.append(feat)
            ogrfeat.Destroy()

        return result