6

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?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
José Gabriel
  • 321
  • 2
  • 7

2 Answers2

7
  • You could use QgsCoordinateReferenceSystem class (as described in this post):

    from qgis.core import QgsCoordinateReferenceSystem, QgsCoordinateTransform, QgsPoint
    
    old_crs = QgsCoordinateReferenceSystem(3857)
    new_crs = QgsCoordinateReferenceSystem(4326)
    tr = QgsCoordinateTransform(old_crs, new_crs)
    transform_points = tr.transform(QgsPoint(5062443.00656, -952576.546977))
    
    print transform_points
    >>> (45.4767,-8.52551)
    

  • Or use the osgeo.osr.SpatialReference class:

    from osgeo import osr
    
    old_crs = osr.SpatialReference() 
    old_crs.ImportFromEPSG(3857) 
    new_crs = osr.SpatialReference() 
    new_crs.ImportFromEPSG(4326) 
    transform = osr.CoordinateTransformation(old_crs,new_crs) 
    transform_points = transform.TransformPoint(5062443.00656, -952576.546977)
    
    print transform_points[0], transform_points[1] 
    >>> 45.4766992778 -8.5255050757
    

Notice how in both cases, the x and y coordinates returned are 45.4766992778 and -8.5255050757 respectively which differ slightly from those in your question.

Joseph
  • 75,746
  • 7
  • 171
  • 282
  • 1
    You are every where ! Good to know for osgeo ! Very nice post. sorry for repeating same thing. We post almost at the same time. +1 – SIGIS Nov 06 '17 at 13:56
  • @SIGIS - I don't think I post that often but thanks :). Also, your format is closer to the original posters so no need to apologise =) – Joseph Nov 06 '17 at 13:59
  • 1
    my x2 and y2 where wrong sorry. Thank you to both. – José Gabriel Nov 06 '17 at 14:15
7

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
SIGIS
  • 912
  • 7
  • 19