pythonpolygonkmlsimplekml

How to create several polygons with simple kml python?


I am trying to create a program to draw polygons in a kml with simpleKML in python, the idea is to send a list of coordinates to create polygons in different zones, but it is not working for me, could you tell me what I am doing wrong...

this is my code:

def Draw(Coordenate):
for cor in Coordenate:
    print(cor[0][0], cor[0][1])
    pol = kmlA.newpolygon(name=str(cor[0]))
    pol.outerboundaryis =[  (float(cor[0][0]), float(cor[0][1])), 
                            (float(cor[1][0]), float(cor[1][1])), 
                            (float(cor[2][0]), float(cor[2][1])), 
                            (float(cor[3][0]), float(cor[3][1])), 
                            (float(cor[4][0]), float(cor[4][1])),  
                        ]
    pol.style.polystyle.color='990000ff'
    pol.style.polystyle.outline = 0
    pnt = kmlA.newpoint(name="Kirstenbosch StyleMap", coords=[cor[0]])
kmlA.save("C:/test2.kml")   

the list "cordenate" has this form enter image description here


Solution

  • If the argument to Draw() function is a list of polygon coordinates then as you iterate the list, only need to refer to the coordinate list as the outerboundaryis for a new polygon.

    Note the longitude coordinate must appear before the latitude in the coordinate tuples.

    import simplekml
    
    def Draw(Coordenate):
        for cor in Coordenate:
            pol = kml.newpolygon(name=str(cor[0]))
            pol.outerboundaryis = cor
            pol.style.polystyle.color = '990000ff'
            pol.style.polystyle.outline = 0
            pnt = kml.newpoint(name="Kirstenbosch StyleMap", coords=[cor[0]])
    
    kml = simplekml.Kml()
    
    # example coordinates for 2 polygons
    x1 = -77.039430
    y1 = 38.895441
    x2 = -77.033689
    y2 = 38.892156
    
    xx1 = -77.035526
    yy1 = 38.889736
    xx2 = -77.034781
    yy2 = 38.889165
    
    Draw([[(x1, y1),(x2, y1), (x2, y2), (x1, y2), (x1, y1)],
          [(xx1, yy1), (xx2, yy1), (xx2, yy2), (xx1, yy2), (xx1, yy1)]])
    kml.save("test2.kml")