Graphics Reference
In-Depth Information
vertexCoord,vertex,prevVertex,nextVertex,distSquared = \
feature.geometry().closestVertex(layerPt)
distance = math.sqrt(distSquared)
if distance > tolerance:
return None
else:
return vertex
As you can see, we use the QgsGeometry.closestVertex() method to find the
vertex closest to the given position and then see if that vertex is within the tolerance dis-
tance. If so, we return the vertex index for the clicked-on vertex; otherwise, we return
None .
Notice that this method uses the math.sqrt() function. To be able to use this function,
you'll need to add the following near the top of the module:
import math
With these two new methods defined, we're ready to start implementing vertex snapping.
Here is the signature for the method we are going to write:
snapToNearestVertex(pos, trackLayer, excludeFeature=None)
In this method, pos is the click position (in canvas coordinates), trackLayer is a refer-
ence to our track layer (which contains the features and vertices we need to check), and
excludeFeature is an optional feature to exclude when looking for nearby vertices.
Note
The excludeFeature parameter will be useful when we start editing tracks. We'll use
it to stop a track from snapping to itself.
Upon completion, our method will return the coordinate of the clicked-on vertex. If the
user didn't click anywhere near a feature, or close to a vertex, then this method will return
the click position instead, converted to layer coordinates. This lets the user click on the
map canvas, away from any vertices, to draw new features, while still snapping to an ex-
isting vertex when the user clicks on it.
Search WWH ::




Custom Search