c++projpyproj

Using PROJ C++ API for CRS-to-CRS transformations


pyproj is a language binding for PROJ. The pyproj module provides easy-to-use methods for CRS-to-CRS transformations, For instance, use it to convert global latitude/longitude (degrees) to local coordinates with respect to some coordinate reference system (metres):

>>> from pyproj import Transformer
>>> transformer = Transformer.from_crs(4326, 6677)
>>> transformer.transform(35.9032597, 139.9343755)
(-10728.330840296036, 9120.537451921156)

PROJ provides a C++ API but the documentation is pure crap. There are no sample codes and I couldn't find my way through it. I'd be really appreciative if anyone could give a clue on how to use the C++ API the same way pyproj works for arbitrary transformations.


Solution

  • You can do something like this

    #include <proj.h>
    #include <iostream>
    
    PJ_CONTEXT *C;
    PJ *P;
    
    C = proj_context_create();
    
    P = proj_create_crs_to_crs(C, "EPSG:4326", "EPSG:6677", NULL);
    
    PJ_COORD input_coords,
             output_coords; // https://proj.org/development/reference/datatypes.html#c.PJ_COORD
    
    input_coords = proj_coord(35.9032597, 139.9343755, 0, 0);
    
    output_coords = proj_trans(P, PJ_FWD, input_coords);
    
    std::cout << output_coords.xy.x << " " << output_coords.xy.y << std::endl;
    
    /* Clean up */
    proj_destroy(P);
    proj_context_destroy(C); // may be omitted in the single threaded case
    
    

    Of course, beyond this initial level, you can make whatever function or class wrappers you need. But this reproduces the pyproj example you posted.