原文作者:我辈李想
版权声明:文章原创,转载时请务必加上原文超链接、作者信息和本声明。
前言
simplekml是一个用于创建kml文件的库,里面提供了丰富的功能和样式,这里介绍如何设置相关样式,解决样式不显示的问题。
一、基本样式
常用
kml = simplekml.Kml(name='tianyi map')
pnt = kml.newpoint(name="shanghai", coords=[[121.4222, 31.218123]])
# lon, lat, optional height
pnt.description = "描述信息: 东方"
pnt.style.labelstyle.color = simplekml.Color.red # 设置字体颜色 'ffff0000'
pnt.style.labelstyle.scale = 2 # 设置字体大小
pnt.style.labelstyle.scale = 0.0 # 隐藏字体 name
pnt.iconstyle.icon.href = '' # 取消图标
pnt.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' # 设置图标
pnt.style.iconstyle.scale = 3 # 设置图片的大小
kml.save(file_kml)
二、共享样式
import simplekml
kml = simplekml.Kml()
style = simplekml.Style() # 或者 simplekml.StyleMap()
kml.style = style # 或者 kml.stylemap = stylemap
# 设置Style样式
style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png'
style.linestyle.width = 3
style.polystyle.color = simplekml.Color.rgb(255, 255, 0)
# 设置StyleMap样式
stylemap.normalstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png'
stylemap.normalstyle.linestyle.width = 3
stylemap.normalstyle.polystyle.color = simplekml.Color.rgb(255, 255, 0)
stylemap.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle_highlight.png'
stylemap.highlightstyle.linestyle.width = 5
stylemap.highlightstyle.polystyle.color = simplekml.Color.rgb(255, 0, 0)
point = kml.newpoint(name='Point', coords=[(0,0)])
point.style = style # 或者 point.stylemap = stylemap
三、全局样式
simplekml全局设置需要设置kml.document.style或kml.document.stylemap,如果设置kml.style将导致样式失效(这一点网上课程几乎很少介绍,需要小心)。
1.结果
错误结果
正确结果
2.代码
kml = simplekml.Kml()
kml.document.name = "doc"
# 设置StyleMap样式
stylemap = simplekml.StyleMap()
stylemap.normalstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png'
stylemap.normalstyle.linestyle.width = 3
stylemap.normalstyle.polystyle.color = simplekml.Color.rgb(255, 255, 0)
stylemap.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png'
stylemap.highlightstyle.linestyle.width = 5
stylemap.highlightstyle.polystyle.color = simplekml.Color.rgb(255, 0, 0)
kml.document.stylemap = stylemap
s_folder = kml.newfolder(name="test")
s_folder.stylemap = stylemap
coords = [[110.6183975164221, 19.46456470187252], [110.9040907171277, 19.46494114209082], [110.9039351250598, 19.7273780493985], [110.6177784661397, 19.72699612707156]]
s_polygon = s_folder.newpolygon(name=zf.get("ProductID"), outerboundaryis=coords, tessellate="1")
s_polygon.stylemap = stylemap
kml.save("test.kml")