I'm trying to find the closest point on a line to another point as in this post. However when I try to write the result as a shapefile I get an error:
TypeError: QgsVectorFileWriter.addFeature(QgsFeature, QgsFeatureRendererV2 renderer=None, QGis.UnitType outputUnit=QGis.Meters): argument 1 has unexpected type 'Point'
import shapely
from shapely.wkt import *
from shapely.geometry import *
from qgis.gui import *
from qgis.core import *
from PyQt4.QtCore import Qt
lineLayer = iface.mapCanvas().layer(0)
pointLayer = iface.mapCanvas().layer(1)
canvas = iface.mapCanvas()
spIndex = QgsSpatialIndex()
lineIter = lineLayer.getFeatures()
provider = pointLayer.dataProvider()
fields = provider.fields()
writer = QgsVectorFileWriter('Test.shp', 'CP1250', fields, provider.geometryType(), provider.crs(), "ESRI Shapefile")
for lineFeature in lineIter:
spIndex.insertFeature(lineFeature)
pointIter = pointLayer.getFeatures()
for feature in pointIter:
ptGeom = feature.geometry()
pt = feature.geometry().asPoint()
nearestIds = spIndex.nearestNeighbor(pt,1)
featureId = nearestIds[0]
nearestIterator = lineLayer.getFeatures(QgsFeatureRequest().setFilterFid(featureId))
nearFeature = QgsFeature()
nearestIterator.nextFeature(nearFeature)
shplyLineString = shapely.wkt.loads(nearFeature.geometry().exportToWkt())
shplyPoint = shapely.wkt.loads(ptGeom.exportToWkt())
dist = shplyLineString.distance(shplyPoint)
shplySnapPoint = shplyLineString.interpolate(shplyLineString.project(shplyPoint))
snapGeometry = QgsGeometry.fromWkt(shapely.wkt.dumps(shplySnapPoint))
r = QgsRubberBand(canvas,QGis.Point)
r.setColor(Qt.red)
r.setToGeometry(snapGeometry,pointLayer)
writer.addFeature(shplySnapPoint)
del writer