how to change shape color using `simple_kml` in python

850 Views Asked by At

I'm using simple_kml library to generate a kml file with data sent from drawing manager on google Maps using Javascript, everything goes fine except the color of the shape .. the color send in this format #ec0909, and here is how am trying to add it to the shape:

ls = kml.newlinestring(name="Polyline")
ls.coords = [(latlng['lng'], latlng['lat']) for latlng in shape['coordinates']]
ls.description = shape['info_box']
print(f"THE COLOR IS {color_code}") #returns #ec0909
ls.style.polystyle.color = color_code

as you see the color should be red .. but it is shown as blue/red shaded color.

enter image description here

enter image description here

2

There are 2 best solutions below

0
On

color_code needs to not contain the pound sign character; your comment makes it seem like that string is #ec0909 but it needs to be ec0909. Beyond that, you’re working on a kml.LineString object and not a kml.Polygon object, so I think you need to set the color using ls.style.linestyle.color instead of ls.style.polystyle.color.

Hope that helps,

—K

EDIT: see more here and consider you may need to convert a hex string using kml.Color.hex() in your assignment, or include alpha codes to make color_code into the string ec0909ff.

0
On

If this is expecting a KML color code, then not only do you need to remove the # sign and add alpha/opacity, you also need to reverse the 3 colors.

KML does not use "normal" color order (RGB), instead it is in reversed order of Blue, Green, Red, with alpha/opacity in the front, for: AABBGGRR, where AA is alpha, BB is blue, GG is Green and RR is Red.

For more info see the documentation for the <color> tag, here: https://developers.google.com/kml/documentation/kmlreference#elements-specific-to-colorstyle

specifically this line:

The order of expression is aabbggrr

For the color you indicated, the KML will need to end up containing: ff0909ec.

That said, it looks like simple_kml can take color codes in a number of formats depending on which method you use, so pick the right one in the docs: https://simplekml.readthedocs.io/en/latest/constants.html#color