def handle(self, *args, **options):
     filename = os.path.join(settings.KMLDIR, "territory_boundaries.kml")
     
     # Parse kml_str
     kml = parseString(open(filename).read())
     added = 0
     failed = 0
     
     print "Loading boundaries from: %s" % filename
     
     for placemark in kml.getElementsByTagName("Placemark"):
         polygon = placemark.getElementsByTagName("Polygon")
         try:
             kml_str = polygon[0].toxml()
             sys.stdout.write('.')
         except:
             sys.stdout.write('!')
             failed += 1
             continue
         
         added += 1
         b = Boundary()
         b.set_poly_from_kml_str(kml_str)
         b.boundary_type_id = 5
         b.save()
     
     print "\nFinished!"
     print "Successfully added: %d" % added
     print "Failed to add: %d" % failed
    def handle(self, *args, **options):
        constituencies = {}
        for c in Constituency.objects.all():
            constituencies[reduceName(c.name)] = c
        for b in Boundary.objects.all():
            b.delete()
        for f in ['boundaries/data/england.kml', 
                  'boundaries/data/wales.kml', 
                  'boundaries/data/scotland.kml', 
                  'boundaries/data/northern_ireland.kml']:
            places = parse(f).getElementsByTagName("Placemark")
            for place in places:
                name = place.getElementsByTagName("name")[0].childNodes[0].toxml()
                v = []
                for coords in place.getElementsByTagName("coordinates"):
                    points = []
                    north = - google_dist
                    south = google_dist
                    east = - google_dist
                    west = google_dist
                    for coord in coords.childNodes[0].toxml().split(" "):
                        s = coord.split(",")
                        if len(s) == 3:
                            x, y = [float(c) for c in coord.split(",")][:2]
                            p = Point(x, y, srid=4326)
                            p.transform(900913)
                            gx, gy = p.coords
                            if gy > north: north = gy
                            if gy < south: south = gy                    
                            if gx > east: east = gx
                            if gx < west: west = gx
                            points.append((gx, gy))
                    for z in range(maxZoom + 1):
                        pixelsize2 = ((2 * google_dist / 256) / (2 ** z)) ** 2
                        u = []
                        previousX = 1e20
                        previousY = 1e20
                        for x, y in points:
                            if z == maxZoom:
                                u.append("(%f, %f)" % (x, y))
                            elif (x - previousX) ** 2 + (y - previousY) ** 2 > pixelsize2:
                                u.append("(%f, %f)" % (x, y))
                                previousX, previousY = x, y
                        if z != maxZoom and (previousX, previousY) != (x, y):
                            u.append("(%f, %f)" % (x, y))
                        if len(u) > 3:
                            constituency = constituencies[reduceName(name)] #Need to use this function due to slight name mismatches
                            boundary="[%s]" % reduce(lambda x, y: "%s, %s" %(x, y), u).strip()
                            b=Boundary(zoom = z,
                                       constituency = constituency, 
                                       boundary=boundary,
                                       east = east,
                                       west = west,
                                       north = north,
                                       south = south)
                            try:
                                b.save()
                            except: 
 #                               print boundary
                                pass
    def handle(self, *args, **options):
        filename = os.path.join(settings.KMLDIR, "territory_boundaries.kml")

        # Parse kml_str
        kml = parseString(open(filename).read())
        added = 0
        failed = 0

        print "Loading boundaries from: %s" % filename

        for placemark in kml.getElementsByTagName("Placemark"):
            polygon = placemark.getElementsByTagName("Polygon")
            try:
                kml_str = polygon[0].toxml()
                sys.stdout.write('.')
            except:
                sys.stdout.write('!')
                failed += 1
                continue

            added += 1
            b = Boundary()
            b.set_poly_from_kml_str(kml_str)
            b.boundary_type_id = 5
            b.save()

        print "\nFinished!"
        print "Successfully added: %d" % added
        print "Failed to add: %d" % failed
Beispiel #4
0
def kml(args):
    """Load boundary polygons from a KML."""
    
    import sys
    import os
    
    from boundaries.models import Boundary, BoundaryType, BoundariesRelated
    from xml.dom.minidom import parseString    
    import settings
    
    #b = Boundary.objects.all()[0]
    file_path = os.path.join(settings.KMLDIR, args.kmlfilename)
    boundary_type_id = args.boundary_type_id
    
    # file exists?
    if not os.path.exists(file_path):
        print "File not found: %s" % file_path
        sys.exit()
    
    # boundary_type id valid?
    try:
        boundary_type_id = BoundaryType.objects.get(id=boundary_type_id).id
    except:
        print  "Invalid Boundary Type ID: %d" % boundary_type_id
        sys.exit()
    
    print file_path, boundary_type_id
    
    # Parse kml_str
    kml = parseString(open(file_path).read())
    added = 0
    failed = 0
    
    print "Loading boundaries from: %s" % file_path
    
    for placemark in kml.getElementsByTagName("Placemark"):
        polygon = placemark.getElementsByTagName("Polygon")
        try:
            kml_str = polygon[0].toxml()
            sys.stdout.write('.')
        except:
            sys.stdout.write('!')
            failed += 1
            continue
        
        added += 1
        b = Boundary()
        b.set_poly_from_kml_str(kml_str)
        b.boundary_type_id = boundary_type_id
        b.save()
    
    print "\nFinished!"
    print "Successfully added: %d" % added
    if failed:
        print "Failed to add: %d" % failed    
Beispiel #5
0
    def handle(self, *args, **options):
        constituencies = {}
        for c in Constituency.objects.all():
            constituencies[reduceName(c.name)] = c
        for b in Boundary.objects.all():
            b.delete()
        print constituencies.keys()
        for f in [
                'boundaries/data/england.kml', 'boundaries/data/wales.kml',
                'boundaries/data/scotland.kml',
                'boundaries/data/northern_ireland.kml'
        ]:
            print f
            places = parse(f).getElementsByTagName("Placemark")
            for place in places:
                name = place.getElementsByTagName(
                    "name")[0].childNodes[0].toxml()
                print name
                v = []
                for coords in place.getElementsByTagName("coordinates"):
                    points = []
                    north = -google_dist
                    south = google_dist
                    east = -google_dist
                    west = google_dist
                    for coord in coords.childNodes[0].toxml().split(" "):
                        s = coord.split(",")
                        if len(s) == 3:
                            x, y = [float(c) for c in coord.split(",")][:2]
                            p = Point(x, y, srid=4326)
                            p.transform(900913)
                            gx, gy = p.coords
                            if gy > north: north = gy
                            if gy < south: south = gy
                            if gx > east: east = gx
                            if gx < west: west = gx
                            points.append((gx, gy))
                    for z in range(maxZoom + 1):
                        pixelsize2 = ((2 * google_dist / 256) / (2**z))**2
                        u = []
                        previousX = 1e20
                        previousY = 1e20
                        for x, y in points:
                            if z == maxZoom:
                                u.append("(%f, %f)" % (x, y))
                            elif (x - previousX)**2 + (
                                    y - previousY)**2 > pixelsize2:
                                u.append("(%f, %f)" % (x, y))
                                previousX, previousY = x, y
                        if z != maxZoom and (previousX, previousY) != (x, y):
                            u.append("(%f, %f)" % (x, y))
                        if len(u) > 3:
                            constituency = constituencies[reduceName(
                                name
                            )]  #Need to use this function due to slight name mismatches
                            boundary = "[%s]" % reduce(
                                lambda x, y: "%s, %s" % (x, y), u).strip()
                            b = Boundary(zoom=z,
                                         constituency=constituency,
                                         boundary=boundary,
                                         east=east,
                                         west=west,
                                         north=north,
                                         south=south)
                            try:
                                b.save()
                            except:
                                print boundary

                if len(v) >= 1:
                    print "'%s'" % name