Exemple #1
0
    def get_layer_points_postgis_ogr(self, layer, bbox_str, max_features):
        # print("Content-type: text/plain\n\n")

        points = []

        # "the_geom from (select g.id, g.point as the_geom from gw_tracepoint g where g.point && GeomFromText('POLYGON((-4.275557 50.242394,-4.275557 54.685361,14.115557 54.685361,14.115557 50.242394,-4.275557 50.242394))',4326) order by random() limit 3000) as subquery using unique id using srid=4326"
        bbox_arr = [float(x) for x in bbox_str.split(",")]

        box_polygon = (
            str(bbox_arr[0])
            + " "
            + str(bbox_arr[1])
            + ","
            + str(bbox_arr[0])
            + " "
            + str(bbox_arr[3])
            + ","
            + str(bbox_arr[2])
            + " "
            + str(bbox_arr[3])
            + ","
            + str(bbox_arr[2])
            + " "
            + str(bbox_arr[1])
            + ","
            + str(bbox_arr[0])
            + " "
            + str(bbox_arr[1])
        )
        # box_polygon = "-4.275557 50.242394, -4.275557 54.685361, 14.115557 54.685361, 14.115557 50.242394, -4.275557 50.242394"
        sql = (
            "select AsBinary(point) as wkb_geometry from gw_tracepoint where point && GeomFromText('POLYGON(("
            + box_polygon
            + "))',4326) order by random() limit "
            + str(max_features)
        )
        connProp = "PG: host=localhost dbname='georambling' user='******' password='******'"
        conn = ogr.Open(connProp)
        result = conn.ExecuteSQL(sql)

        ftCnt = result.GetFeatureCount()
        printtime("PostGIS query done cnt=" + str(ftCnt))
        # print ftCnt
        try:
            for i in range(0, ftCnt):
                feat = result.GetFeature(i)
                feat_pt = feat.GetGeometryRef()
                point = Point((feat_pt.GetY(), feat_pt.GetX()))
                points.append(point)

                # printtime('feat(' + str(i) + ') x=' + str(feat_pt.GetX()) + ' y=' + str(feat_pt.GetY()))
        except Exception:
            # print Exception.message
            # print sys.exc_info()
            return points

        return points
Exemple #2
0
    def get_layer_points_postgis(self, layer, bbox_str, max_features):
        # print("Content-type: text/plain\n\n")

        points = []

        name = "mapglow"
        dsn = layer.connection  # e.g. "host=localhost dbname='dbname' user='******' password='******'"
        table = layer.getMetaData("mapglow_table_name")
        fid = layer.getMetaData("gml_featureid")  # defaults to ogc_fid
        geometry = layer.getMetaData("mapglow_table_geom_col")  # defaults to the_geom
        srid = 4326  # defaults to 4326
        encoding = "utf-8"  # defaults to utf-8
        attribute_cols = "rating"  # optional
        order = "random()"  # optional

        #    try:
        pg = PostGIS(name=name, fid=fid, geometry=geometry, srid=srid, order=order, layer=table, dsn=dsn)
        pg.begin()

        class Action:
            id = None
            attributes = None
            bbox = [float(x) for x in bbox_str.split(",")]
            maxfeatures = max_features
            startfeature = None

        action = Action()

        features = pg.select(action)
        # print(str(features[0].get_geo()['coordinates'][0 ]))

        ftCnt = features.__len__()
        printtime("PostGIS query done cnt=" + str(ftCnt))
        # print ftCnt
        try:
            for i in range(0, ftCnt):
                feat = features[i]
                feat_pt = feat.get_geo()
                point = Point((feat_pt["coordinates"][1], feat_pt["coordinates"][0]))
                points.append(point)

                # printtime('feat(' + str(i) + ') x=' + str(feat_pt.GetX()) + ' y=' + str(feat_pt.GetY()))
        except Exception:
            # print Exception.message
            # print sys.exc_info()
            return points

        return points
Exemple #3
0
 def startElement(self, name, attrs):
     # printtime('startElement=' + name)
     if name == "gml:pos":
         # Found coordinate: next content will be lon/lat
         self.coord_elm = True
     elif name == "wfs:FeatureCollection":
         self.numberOfFeatures = int(attrs["numberOfFeatures"])
         self.skip_count = (self.numberOfFeatures / self.max_features) + 1
         printtime(
             "max_features="
             + str(self.max_features)
             + " nroffeatures="
             + str(self.numberOfFeatures)
             + " skip_count="
             + str(self.skip_count)
         )
Exemple #4
0
    def wms_getheatmap_req(self, wms_req):
        # http://mapserver.org/ogc/mapscript.html#python-examples
        # test url
        # http://mapglow.org/wms/?service=WMS&request=GetMap&bbox=4.95,52,5.6,52.3&version=1.1.0&layers=tracepoints&srs=EPSG:4326&format=image/png&width=400&height=400
        #    print("Content-type: text/plain\n\n")

        bbox = wms_req.getValueByName("BBOX")
        layer = wms_req.getValueByName("LAYERS")
        srs = wms_req.getValueByName("SRS")
        width = float(wms_req.getValueByName("WIDTH"))
        height = float(wms_req.getValueByName("HEIGHT"))

        # CREATE WKT STRING OF POINT COORDS
        bbox_arr = bbox.split(",")
        wktLL = "POINT(%s %s)" % (bbox_arr[0], bbox_arr[1])
        wktUR = "POINT(%s %s)" % (bbox_arr[2], bbox_arr[3])

        # CREATE PROJECTION OBJECTS
        google = osr.SpatialReference()
        google.ImportFromEPSG(900913)
        wgs84 = osr.SpatialReference()
        wgs84.ImportFromEPSG(4326)

        # CREATE OGR POINT OBJECT, ASSIGN PROJECTION, REPROJECT
        pointLL = ogr.CreateGeometryFromWkt(wktLL)
        pointLL.AssignSpatialReference(google)
        pointLL.TransformTo(wgs84)
        pointUR = ogr.CreateGeometryFromWkt(wktUR)
        pointUR.AssignSpatialReference(google)
        pointUR.TransformTo(wgs84)

        bbox = "%f,%f,%f,%f" % (pointLL.GetX(), pointLL.GetY(), pointUR.GetX(), pointUR.GetY())
        bboxLL = "%f,%f,%f,%f" % (pointLL.GetY(), pointLL.GetX(), pointUR.GetY(), pointUR.GetX())

        # Do not use internal WFS (too slow)
        # points = self.get_layer_points_wfs(layer, bbox, max_features)

        # Get points from the layer (direct layer query)

        layerObj = self.map.getLayerByName(layer)
        points = []
        if layerObj:
            # see if layer has configured feature density
            # this determines max number of features for Layer query
            feature_density = float(layerObj.metadata.get("mapglow_feat_density", "0.002"))

            # calculate max features for Layer query
            max_features = int(round(feature_density * width * height))

            # get array of Point objects from Layer
            printtime("START - get points from layer max_features=" + str(max_features))
            points = self.get_layer_points(layerObj, bbox, max_features)
            printtime("Got " + str(len(points)) + " points from layer")

        # No points: generate transparent overlay image using standard MS dispatch
        if len(points) <= 0:
            mapscript.msIO_installStdoutToBuffer()

            # MS does not like the heatmap-style STYLES
            wms_req.setParameter("STYLES", "")

            self.map.OWSDispatch(wms_req)
            print(mapscript.msIO_getStdoutBufferBytes())
            return

        # Get heatmap algoritm+parms
        # Now 1 type in STYLES, e.g. 'heat/seth/red-yellow-green/12/0.5'
        # TODO: parameters are heatmap-type specific
        (heat, heatmap_type, gradient, radius, decay) = wms_req.getValueByName("STYLES").split("/")

        # Just to protect ourselves from blowing up
        if int(radius) > 20:
            radius = "20"

        # check how gradient is specified: either a gradient file or a range of doubles (stop, R, G, B, A)
        gradient_path = self.root_dir + "config/gradients/gradient-" + gradient + ".png"
        if os.path.exists(gradient_path):
            # Gradient as file
            gradient_option_name = "--gradient"
            gradient_option_value = gradient_path
        else:
            # Gradient as range of doubles (stop, R, G, B, A), (stop, R, G, B, A),...
            # each of value double between 0..1
            # e.g. 0,1,1,0,1, 0.75,1,0,0,1, 0.9,1,1,0
            gradient_option_name = "--gradient_color_srgba"
            gradient_option_value = gradient

        # Assemble arguments
        args = [
            "--web",
            "--points_arr",
            "--radius",
            radius,
            "--decay",
            decay,
            "--width",
            wms_req.getValueByName("WIDTH"),
            "--height",
            wms_req.getValueByName("HEIGHT"),
            gradient_option_name,
            gradient_option_value,
            "--extent",
            bboxLL,
        ]

        # Creates and sends the heatmap
        main(args, points)