Oihane Kamara Esteban Oihane Kamara Esteban - 23 days ago 6
Python Question

Converting from UTM to LongLat using Proj4 in C++

I've been going around this issue for days, but haven't been able to find an explanation to what I am doing wrong. I hope you can lend me a hand.

I have a set of UTM coordinates

(epsg:23030)
that I want to convert to LongLat Coordinates
(epsg:4326)
by using the proj4 library for C++
(libproj-dev)
. My code is as follows:

#include "proj_api.h
#include <geos/geom/Coordinate.h>

geos::geom::Coordinate utm2longlat(double x, double y){

// Initialize LONGLAT projection with epsg:4326
if ( !( pj_longlat = pj_init_plus("+init=epsg:4326" ) ) ){
qDebug() << "pj_init_plus error: longlat";
}

// Initialize UTM projection with epsg:23030
if ( ! (pj_utm = pj_init_plus("+init=epsg:23030" ) ) ){
qDebug() << "pj_init_plus error: utm";
}

// Transform UTM projection into LONGLAT projection
int p = pj_transform( pj_utm, pj_longlat, 1, 1, &x, &y, NULL );

// Check for errors
qDebug() << "Error message" << pj_strerrno( p ) ;

// Return values as coordinate
return geos::geom::Coordinate(x, y)
}


My call to the function
utm2longlat
:

...
// UTM coordinates
double x = 585363.1;
double y = 4796767.1;
geos::geom::Coordinate coord = utm2longlat( x, y );

qDebug() << coord.x << coord.y;

/* Result is -0.0340087 0.756025 <-- WRONG */


In my example:


  • I know that UTM coordinates
    (585363.1 4796767.1)
    refer to LongLat coordinates
    (-1.94725 43.3189)
    .

  • However, when called, the function returns a set of wrong coordinates:
    (-0.0340087 0.756025 )
    .



I was wondering if I had any misconfiguration when initializing the projections, so I decided to test the Proj4 Python bindings
(pyproj)
, just to test whether I got the same wrong coordinates... and curiously, I got the good ones.

from pyproj import Proj, transform

// Initialize UTM projection
proj_utm = Proj(init='epsg:23030')
// Initialize LongLat projection
proj_lonlat = Proj(init='epsg:4326')

x_utm, y_utm = 585363.1, 4796767.1

x_longlat, y_longlat = transform(proj_utm, proj_lonlat, x_utm, y_utm)

// Print results
print "original", x_utm, y_utm
print "utm2lonlat", x_longlat, y_longlat

/* Result is -1.94725 43.3189 <-- CORRECT */


From what I understand
pyproj
is a set of Cython bindings over the
Proj4
library, so I am using the same core in both programming languages.

Do you have any clue as to what could be wrong? Am I missing some type of conversion in the C++ function?

Thanks in advance.

Answer

The result seems to be correct to me, but it's returned in radians instead of degrees. Convert the result to degrees and check again.