Ogr/gmt - using aspatial field for label

Feels trivial, but still…

My .gmt file consists of a series ff polygons, e.g.

# @D17|1|17|00256|"text"
# @P
2.881271 56.381291
2.695486 56.528523
2.611864 56.594331
2.528616 56.767993
2.444595 56.941595
2.41605332101142 57.0
3 57
3.0 56.286289123311
2.881271 56.381291

I would like to use one of the aspatial fields (the field containing 00256 in this case) as text for plotting a label. But how to do this?
Getting the text out and then figuring out the centroid as plotting position sounds like a plan, but seems intricate for such an easy task (…)

Easy task for the user if that was all implemented. text does no take data, computing a centroid, then gets a string and plots it. gmt spatial can compute centroids, but not sure how then to get the text item out for a polygon.

Thanks Paul. That was my thought as well; spatial to create centroid then extract the needed text. Just had to ask if there was an easy way.

And I guess you don’t want me (yet) to investigate for a one (two) liners solution, right? :slight_smile:

1 Like

One day, @Joaquim. One day :slight_smile:

For now, I used QGIS with it’s spatialite(?) support and ran sql to produce a simple output of x, y, text (x and y of the centroid of the polygon), which I then exported as a gmt chewable csv file;

SELECT st_x(Centroid(geom)), st_y(Centroid(geom)), text FROM table
1 Like

Petty, because ogr2ogr is wrapped so it should really be a one-liner. Except that I’m still to learn how to use it and hidden bugs are always around the corner.

I’m fairly sure I could’ve done this with a one liner in ogr2ogr as well. But, it’s so nice to get a visual confirmation that what you’re doing (at least) looks right.

You can run your spatialite code directly in ogr2ogr, as it is usually built with spatialite support:

ogr2ogr -f CSV filename.csv -dialect SQLite -sql "SELECT ST_X(Centroid(GEOMETRY)), ST_Y(Centroid(GEOMETRY)), text FROM filename" filename.gmt

you can even add a “layer creation option” -lco SEPARATOR=TAB or SPACE to skip handling commas.

1 Like

Thanks @mkononets!

One click solution in QGIS is Vector -> Geometry tools -> Centroids. Good thing here is that the resulting file also contains all your metadata so that you can pass x, y, MyLabelAttribute to gmt text

1 Like

Thanks for the tips @chhei-s.

very good remark. It is possible to do the same on command-line using * (wildcard) in SELECT:

ogr2ogr -f CSV filename.csv \
        -dialect SQLite \
        -sql "SELECT ST_X(Centroid(GEOMETRY)), ST_Y(Centroid(GEOMETRY)), * FROM filename" \