[GIS] Projection: conversion of coordinate pairs in Python

coordinate systemepsgpyqgis

Google Translated

I am using QGIS and wish to automate the export of a map (an existing project) to which I add a vector layer (representing a construction zone) in pdf format. The problem is:

The map I have available is referenced by the EPSG 2154 (OTF), but the details I want to create my layer are in 4326 (WGS84). The PDF produced by my program only displays the layer that I created, even if I specify what EPSG I'm working in. Looking at the map in QGIS, the construction area is properly aligned to the other layers. I am lost… If I convert this data manually before starting the program, and I state that now it is in EPSG 2154, everything works.

Is there a Python library for performing conversions of EPSG to another directly? Or is it possible to change the EPSG an existing project? (Perhaps in layers?)

I am working with QGIS 2.8.2

Here is the extract of what I have tried so far:

 points = []

# On ajoute maintenant les points un a un

for point in poly.liste_points:
    layerPoint = QgsPoint( point[0], point[1] )
    points.append( layerPoint )

# On cree la "coloration" a l'interieur du polygone en creant une couche

layer =  QgsVectorLayer('Polygon?crs=EPSG:'+EPSG, 'ZoneChantier' , "memory")
pr = layer.dataProvider() 
polyg = QgsFeature()

polyg.setGeometry(   QgsGeometry.fromPolygon( [points] )   )
pr.addFeatures([polyg])


# On gere la couleur

# ******************************************************************************************************************************************* #
renderer = layer.rendererV2()
# COLOR et COLOR_BORDER sont definies dans config.py
symbol = QgsFillSymbolV2.createSimple(   { str('style'): str('solid'), str('color'): COLOR, str('color_border'): COLOR_BORDER }   )
renderer.setSymbol(symbol)
layer.updateExtents()
# ******************************************************************************************************************************************* #

# Enfin, on ajoute la couche au reste de la carte

QgsMapLayerRegistry.instance().addMapLayers([layer])
iface.mapCanvas().updateFullExtent()

Poly is an instance of a class containing the coordinates of the site area to trace, COLOR and COLOR_BORDER are global variables defined in another file. EPSG is, as its name suggests, the variable containing the EPSG in the form of string.


Je débute sur QGIS et je souhaite automatiser l'exportation d'une carte (d'un projet déjà existant) à laquelle je rajoute une couche vectorielle (représentant une zone de chantier) sous format pdf. Le problème est le suivant:

La carte que j'ai à disposition est référencée par l'EPSG 2154 (OTF), mais les coordonnées que je reçois pour créer ma couche sont en 4326 (WGS84). Le pdf ressorti par mon programme n'affiche que la couche que j'ai créée, même si je précise bien dans quel EPSG je travaille. En observant la carte sur QGIS, la zone de chantier est pourtant correctement superposée aux autres couches, je suis perdu… Si je convertis ces données manuellement avant de lancer le programme, et que je précise que l'EPSG est maintenant le 2154, tout fonctionne correctement.

Existe-t-il une bibliothèque Python permettant d'effectuer les conversions d'un EPSG à un autre directement ? Ou est-ce possible de modifier l'EPSG d'un projet existant ? (peut-être couche par couche ??)

Je travaille avec QGIS 2.8.2

Voici l'extrait de programme où je crée ma couche:

 points = []

# On ajoute maintenant les points un a un

for point in poly.liste_points:
    layerPoint = QgsPoint( point[0], point[1] )
    points.append( layerPoint )

# On cree la "coloration" a l'interieur du polygone en creant une couche

layer =  QgsVectorLayer('Polygon?crs=EPSG:'+EPSG, 'ZoneChantier' , "memory")
pr = layer.dataProvider() 
polyg = QgsFeature()

polyg.setGeometry(   QgsGeometry.fromPolygon( [points] )   )
pr.addFeatures([polyg])


# On gere la couleur

# ******************************************************************************************************************************************* #
renderer = layer.rendererV2()
# COLOR et COLOR_BORDER sont definies dans config.py
symbol = QgsFillSymbolV2.createSimple(   { str('style'): str('solid'), str('color'): COLOR, str('color_border'): COLOR_BORDER }   )
renderer.setSymbol(symbol)
layer.updateExtents()
# ******************************************************************************************************************************************* #

# Enfin, on ajoute la couche au reste de la carte

QgsMapLayerRegistry.instance().addMapLayers([layer])
iface.mapCanvas().updateFullExtent()

poly est l'instance d'une classe contenant les coordonnées de la zone de chantier à tracer, COLOR est COLOR_BORDER sont des variables globales définies dans un autre fichier. EPSG est, comme son nom l'indique, la variable contenant l'EPSG sous forme de chaîne de caractère…

Best Answer

You need to use QgsCoordinateReferenceSystem and QgsCoordinateTransform classes. I tried out next code to transform polygon vector layer of next image from EPSG: 32612 to EPSG: 4326.

enter image description here

layer = iface.activeLayer()

crsSrc = QgsCoordinateReferenceSystem(32612)
crsDest = QgsCoordinateReferenceSystem(4326)

xform = QgsCoordinateTransform(crsSrc, crsDest)

feats = [ feat for feat in layer.getFeatures() ]

poly = feats[0].geometry().asPolygon()

poly_reproj = poly

for i, point in enumerate(poly[0]):
    pt = xform.transform(point)
    poly_reproj[0][i] = pt
    print pt

mem_layer = QgsVectorLayer("Polygon?crs=epsg:4326&field=id:integer&index=yes",
                           "layer_memory",
                           "memory")

QgsMapLayerRegistry.instance().addMapLayer(mem_layer)

prov = mem_layer.dataProvider()

feature = QgsFeature()

feature.setGeometry(QgsGeometry.fromPolygon(poly_reproj))

#set attributes values
feature.setAttributes([1])

prov.addFeatures([feature])

After running the code, reprojected layer was adequately produced as a memory layer.

enter image description here

Related Question