I have a PyQGIS script that I'm using to generate a series of maps. These maps are individual frames that will be put together in a video. I would like to add some fancy animations associated with a particular point on the map using video editing software, but to do so, I need to extract the position (in print coordinates/pixels) of a point on the map.
How do I do so?
def print_map():
# create a print layout
layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.pageCollection().page(0).setPageSize(QgsLayoutSize(size.width(), size.height(), QgsUnitTypes.LayoutPixels))
# put the map on the layout at the specific position and scale
map = QgsLayoutItemMap(layout)
map.setCrs(QgsCoordinateReferenceSystem(4326))
layout.addLayoutItem(map)
map.setRect(20, 20, 20, 20) # I don't know what this does, but it is required
map.attemptMove(QgsLayoutPoint(0, 0, QgsUnitTypes.LayoutPixels))
map.attemptResize(QgsLayoutSize(size.width(), size.height(), QgsUnitTypes.LayoutPixels))
map.setExtent(QgsRectangle.fromCenterAndSize(fancy_math(), more_fancy_math(), even_more_fancy_math()))
# I'm looking for a function that does this; target_point is a QgsPointXY in map coordinates and position_on_image should be the number of pixels from the top and left of the exported image
position_on_image = map.getPositionOnImage(target_point)
# export the position for further processing with a video editing program
write_to_csv(position_on_image)
# export the layout too, which also gets loaded into the video editing program
exporter = QgsLayoutExporter(layout)
settings = QgsLayoutExporter.ImageExportSettings()
exporter.exportToImage(filename, settings)
Note: I found QgsLayoutItemMap.mapToItemCoords()
, but it doesn't seem to do what I want (the produced coordinates are not right, and I don't know what it is doing).
EDIT: Using the QTransform map_layout.layoutToMapCoordsTransform().inverted()[0]
produced a value, which when multiplied by exactly 11.8110236221, gave me the correct position in pixels. I don't know what that magic number represents.