dictionaryqmlqt5qtlocation

QML: Draw geofence area on QML Map


Any ideas how to draw custom geofence area in QML (Qt Location module) similar to this:

enter image description here

Something similar to MapCircle or MapPolygon but filled outside of the region? And have custom filling pattern?


Solution

  • You probably can play with one of MapItems, for example MapQuickItem allows you put any QML item inside, for example I use Canvas for that:

    Plugin {
        id: mapPlugin
        name: "osm"
    }
    
    Map {
        id: map
        anchors.fill: parent
        plugin: mapPlugin
        center: QtPositioning.coordinate(59.91, 10.75)
        zoomLevel: 14
    
        MapQuickItem {
            id: marker
            anchorPoint.x: image.width / 2
            anchorPoint.y: image.height / 2
            coordinate: map.center
            sourceItem: Canvas {
                id: image
                width: map.width
                height:  map.height
                onPaint: {
                    var ctx = getContext("2d");
                    ctx.beginPath();
                    ctx.moveTo(0, 0);
                    ctx.lineTo(image.width, 0);
                    ctx.lineTo(image.width, image.height);
                    ctx.lineTo(0, image.height);
                    ctx.lineTo(0, 0);
                    ctx.moveTo(image.width/2 + 50, image.height/2);
                    ctx.arc(image.width/2, image.height/2, 50, 0, 2 * Math.PI,0, true);
                    ctx.closePath();
                    ctx.fillStyle = Qt.rgba(1.0, 0, 0, 0.5);
                    ctx.strokeStyle = "red"
                    ctx.lineWidth = 10;
                    ctx.fill();
                    ctx.stroke();
                }
            }
        }
    }
    

    Pay attention, the arc's counterclockwise is true to make a hole. In the same way you can add images etc. But in a real project I would use some custom QQuickItem based item, just for better performance.