Python QGIS Tutorial: Drawing Marker

Marker is a point on the map which is not a point feature. It just a graphic on the map that can be used to mark a location. In this tutorial we will see how to draw a marker on the QGIS map canvas.

Before drawing a marker we have to define the canvas using QGIS interface with the following expression. Otherwise the marker will not show up.

canvas=iface.mapCanvas()

To draw a marker, we are using QgsVertexMarker class. Therefore we need to create a marker using the class into the canvas.

m1 = QgsVertexMarker(canvas)

After creating the marker, then we can set the marker position with setCenter method. Moreover the color, icon and the width line of the marker can be customized with  other methods as in the following code.

m1.setCenter(QgsPointXY(260,104))
m1.setColor(QColor(255,0, 0)) #(R,G,B)
m1.setIconSize(10)
m1.setIconType(QgsVertexMarker.ICON_X)
m1.setPenWidth(3)

The icon that used in the code was X in red color. There are several type of icons avalailabe:
  • ICON_BOX
  • ICON_CIRCLE
  • ICON_CROSS
  • ICON_DOUBLE_TRIANGLE
  • ICON_NONE
  • ICON_X
If you want to change the icon, just change the icon type in the fourth line with a type above. The icon looks like as in figure 1. Must be remember, every time you want to create a maker, a new marker must be defined using the QgsVertexMarker class.

Marker icon type QGIS
Figure 1. Marker icon type
Lastly the marker can be hidden and shown using hide and show method. So the expression will be like this.

m1.hide() # to hide a marker
m1.show() # to show a marker

Take a look the QGIS Python API documentation to learn more about QgsVertexMarker class. 

Related Posts
Disqus Comments