I am making a layout export function and I would like to create a QgsLayoutItemLabel at a given latitude and longitude. But in QgsLayout the position is relative xy (150,100).

Is there a way to convert map coordinates to layout positions?


Well, I find it.

def map_coords_to_position(self, mapx, mapy) -> QPointF:
    ppwu = self.map.pagePositionWithUnits();
    mtic = self.map.mapToItemCoords(QPointF(mapx, mapy))
    return QPointF(mtic.x() + ppwu.x(), mtic.y() + ppwu.y())

self.map is a QgsLayoutItemMap.

For example, you could add a polygon to a map in layout like this.

geom = QgsGeometry.fromWkt(wkt)
wkb_type = geom.wkbType()
if wkb_type == QgsWkbTypes.Polygon:
    p = QPolygonF()
    for v in geom.vertices():
        new_pt = self.map_coords_to_position(v.x(), v.y())
        p.append(QPointF(new_pt.x(), new_pt.y()))
    polygon = QgsLayoutItemPolygon(p, self.layout)            

It is tested in QGIS 3.4.2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.