2

I have written a function that builds a new layer from from a gpx file which is read using pygpx. It runs and the new layer appears in QGIS with all the attributes correct.

Initially I created the layer with a crs of epsg:4326 since the data was lat and lon but when I try and cut and paste the points into my master table I get a message that no points were pasted and no hint why (I have looked in the log).

I now want to try to create the layer in my project crs to see if that fixes the problem but for which I presumably need to transform the points using tr = QgsCoordinateTransform(sourceCrs, destCrs) as described at Transforming single QgsGeometry object from one CRS to another using PyQGIS?

What I can't figure out is how specify the source and dest crs. I tried supplying strings -- there were no errors but it does not seem to do anything. The call to transform returns 0.

    tr = QgsCoordinateTransform('epsg:4326', 'epsg:2193')
    ...
    point = QgsGeometry.fromPoint(QgsPoint( wp.longitude, wp.latitude))
    point.transform( tr )
    fet.setGeometry( point )
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Russell Fulton
  • 2,994
  • 3
  • 31
  • 55
  • Issue is because parameters in your QgsCoordinateTransform object are strings and they must be QgsCoordinateReferenceSystem objects. – xunilk Jul 29 '17 at 14:52
  • Note that there are other issues with this code in the question apart from the parameters to QgsCoordinateTransform. Don't copy anything from this! The code in Xunilk's answer works! – Russell Fulton Jul 29 '17 at 21:20

1 Answers1

1

Issue is because parameters in your QgsCoordinateTransform object are strings and they must be QgsCoordinateReferenceSystem objects. To solve that (for an arbitrary point in New Zealand):

point = QgsPoint(175.8687, -38.7253)

#source crs
crsSrc = QgsCoordinateReferenceSystem(4326)
#target crs
crsDest = QgsCoordinateReferenceSystem(2193)

xform = QgsCoordinateTransform(crsSrc, crsDest)

pt = xform.transform(point)

print pt[0], pt[1]

it was printed:

1849386.27243 5709798.98144

By using QuickWKT plugin, I visualized that point in QGIS (OTF enabled) and it is at right position:

enter image description here

xunilk
  • 29,891
  • 4
  • 41
  • 80