[GIS] Convert from EPSG 3857 to EPSG 4326 QGIS2.18

convertcoordinate systempyqgisqgis-plugins

I need to convert EPSG 3857 to EPSG 4326 in a plugin.

            #example EPSG 3857
            x = 5062443.00656
            y = -952576.546977
            #convert here to EPSG 4326
            #where x2 =41.3387949319,
            #where y2 = -8.55714071443
            return x2,y2 #return in EPSG 4326

something like the code above. Is there a way to do that?

Best Answer

To convert with Qgis API you need to 2 class QgsCoordinateReferenceSystem and QgsCoordianteTransform here them in action :

#example EPSG 3857
src_crs = QgsCoordinateReferenceSystem(3857)
dest_crs = QgsCoordinateReferenceSystem(4326)
xform = QgsCoordinateTransform(src_crs, dest_crs)
x = 5062443.00656
y = -952576.546977
point = QgsPoint(x, y)
#convert here to EPSG 4326
pt_reproj = xform.transform(point)
#where x2 =41.3387949319,
#where y2 = -8.55714071443
#but mine return QgsPoint(45.4766992777683,-8.52550507570475)
return pt_reproj.x(),pt_reproj.y() #return in EPSG 4326