Monday, 19 March 2018

gdal - Styling KML through LIBKML layer creation options


I am exporting a layer from PostgreSQL to KML using ogr2ogr.


I get a workable KML with a series of features (Placemarks). Here is a simplified example of a feature. (I took out the long list of polygon points to simplify the length of the geometry).



FirstFeature
A map feature


myunit
ffe9e9e9




[array of coordinates]




I would like to set the layer creation options such that it will refer to the 8bit hex-code provided by the hexcolor attribute. By default, ogr2ogr seems to be styling all polygon features as red lines with transparent fill (see above ). I instead want the style such that the section becomes...




Answer



Your secret weapon is to create a field in your layer called OGR_STYLE. The ogr LIBKML driver then interprets this to style the output s. The relevant documentation is at https://www.gdal.org/ogr_feature_style.html, https://www.gdal.org/drv_libkml.html, and of course https://www.gdal.org/ogr2ogr.html for invocation (though it works from Python too).


If OGR_STYLE is of the form "@stylename", it will get converted into #stylename in KML. You can than define the styling for it in KML as you wish.



Alternately, if OGR_STYLE uses the language described in the first link above, it is (reasonably) translated into , etc. For instance, for a lineString layer, I just tested (with an export from QGIS desktop, actually) and OGR_STYLE set to PEN(c:#0000ff,w:5px) turns into


 
ffff0000
5


For polygons, you'll use BRUSH(fc:...) for the fill in addition to PEN(c:...) for the border.


You don't mention it, but if you are displaying your layer in e.g. QGIS desktop, you might wonder if you can carry over the QGIS displayed styling directly. That styling is not stored in the layer data, so you can't using ogr2ogr. With the right settings, you can try to do so if exporting from QGIS or using PyQGIS calls. However, the styling capabilities of different visualization engines (QGIS, Google Earth, etc.) are sufficiently incompatible that this works well only in the simplest of cases. I've found it best to either create the target styling in OGR-style language in the OGR_STYLE field, or to do it as a named in KML.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...