Create QGIS curves from Python API

This article was inspired by the question by a discussion about new QGIS geometries due to the publication of a diagram about main QGIS Python classes.

We choose to demonstrate how you can build a curve with three points using the new QGIS geometry API.

QGIS curve demo

I had some months ago to make a representation for import/export flux for wines. In this case, I choose to use arc.js through Node to generate the curves lines.

As I had published another document to display main parts of the QGIS Python API in another context, I got a feedback from a QGIS dev about using the "old" geometry way within QGIS.

Due to this previous experiments, I choose to investigate how to create curves using QGIS with the new QGIS geometry API.

You will find an example to use the new geometry related class QgsCircularStringV2 to display curves within QGIS.

# Some import are optional depending of the context (code executed through the console or via a plugin)
from qgis.core import QgsCircularStringV2, QgsPointV2, QgsGeometry, QgsVectorLayer, QgsMapLayerRegistry
from qgis.utils import iface

# Begin a new project
iface.newProject()

# Create a QgsCircularStringV2
circularRing = QgsCircularStringV2()
# Set first point, intermediate point for curvature and end point
circularRing.setPoints([
    QgsPointV2(0, 0),
    QgsPointV2(0, 10),
    QgsPointV2(10, 10)]
)

# Check if the geometry has curves
print circularRing.hasCurvedSegments()

# Create geometry using the instance of QgsCircularStringV2
geom_from_curve = QgsGeometry(circularRing)

# Create a feature
fet = QgsFeature()
# Assign the geometry
fet.setGeometry(geom_from_curve)

# Create a memory layer
layer = QgsVectorLayer(
    "LineString?crs=epsg:4326&field=id:integer&field=name:string(20)&index=yes",
    "temporary_points",
    "memory"
)
# Add the layer
QgsMapLayerRegistry.instance().addMapLayer(layer)
# Add the feature to the layer provider
pr = layer.dataProvider()
pr.addFeatures([fet])
# Update extent
layer.updateExtents()

# Zoom to extent
iface.mapCanvas().setExtent(layer.extent())
iface.mapCanvas().refresh()

I didn't inspect thoroughly how to manage the curves bending. Feel free to try out. Any feedback is welcome!

You can look at this new tool that landed in QGIS 2.12 to edit curves.

Finally, you can also look for a database oriented solution to use curves on Geographic Information Systems Stack Exchange

Comments