Abnormal output when using proj4 to transform latlong to UTM
An answer to this question on Stack Overflow.
Question
Following code is tring to transfer latlong to utm for one location point in Japan. However, the utm result is totally abnormal as follow. Could someone help on this? Give an example is better. Thanks. *****0.607968 2.438016 -14*****
#include "proj_api.h"
#include "stdio.h"
main(int argc, char **argv) {
projPJ pj_utm, pj_latlong;
double x = 34.8;
double y = 138.4;
if (!(pj_utm = pj_init_plus("+proj=utm +zone=54 +ellps=WGS84")) ){
printf("pj_init_plus error");
exit(1);
}
if (!(pj_latlong = pj_init_plus("+proj=latlong +ellps=WGS84")) ){
printf("pj_init_plus error");
exit(1);
}
x *= DEG_TO_RAD;
y *= DEG_TO_RAD;
int p = pj_transform(pj_latlong, pj_utm, 1, 1, &x, &y, NULL );
printf("%.2f\t%.2f\n", x, y);
exit(0);
}
Answer
I noticed that you were not checking the error code on pj_transform, so I caught it and checked it myself.
It was returning -14. Negative return codes usually indicate errors.
Some digging in the PROJ.4 documentation revealed that the pj_strerrno function returns the error message associated with an error code. Accordingly, I used the function and discovered that -14 means latitude or longitude exceeded limits.
I checked your code and discovered this:
double x = 34.8;
double y = 138.4;
Clearly, y should be in the range [-90,90]. You have mis-named your coordinates.
Correctly naming your coordinates produces the result 262141.18N 3853945.50E, as expected.
My code is below:
//Compile with: gcc cheese.cpp -lproj
#include <proj_api.h>
#include <stdio.h>
main(int argc, char **argv) {
projPJ pj_latlong, pj_utm;
double y = 34.8;
double x = 138.4;
if (!(pj_latlong = pj_init_plus("+proj=longlat +datum=WGS84")) ){
printf("pj_init_plus error: longlat\n");
exit(1);
}
if (!(pj_utm = pj_init_plus("+proj=utm +zone=54 +ellps=WGS84")) ){
printf("pj_init_plus error: utm\n");
exit(1);
}
x *= DEG_TO_RAD;
y *= DEG_TO_RAD;
int p = pj_transform(pj_latlong, pj_utm, 1, 1, &x, &y, NULL );
printf("Error code: %d\nError message: %s\n", p, pj_strerrno(p));
printf("%.2fN\t%.2fE\n", x, y);
}