如何显示多个标记和路径?

1 投票
1 回答
2003 浏览
提问于 2025-04-16 17:56

我正在使用PyKml这个模块来在我的Python脚本中生成KML文件。我的目标是显示一条由坐标数组组成的路径,同时也想把所有的点显示为标记。目前,我尝试了以下方法,但没有成功。

 doc = K.kml(
        K.Document(
            K.Placemark(
                 K.Point(
                     K.name("pl1"),
                    K.coordinates("52.4858, 25.9218, 1051.05105105")
                ) 
            ),
            K.Placemark(
                K.name("path1"),
                K.LineStyle(
                    K.color(0x7f00ffff),
                    K.width(10)
                ),
                K.LineString(
                    K.coordinates(
                        coord_str
                    )
                )
            )
        )
    )

路径看起来没问题,但当我开始添加标记时,谷歌地图只显示了第一个标记。我该怎么做才能在我的路径上显示所有的标记呢?我需要使用某种元编程(也就是自动在对象定义中添加标记)吗?还是说需要其他的方法?

1 个回答

1

这段话的意思是,你可以遍历这些对象,把每个点和它所连接的线关联起来:

from pykml.factory import KML_ElementMaker as K
from lxml import etree

#line_points here comes from a geojson object
data = json.loads(open('tib.json').read())
line_points = data['features'][0]['geometry']['coordinates']

_doc = K.kml()

doc = etree.SubElement(_doc, 'Document')

for i, item in enumerate(line_points):
    doc.append(K.Placemark(
        K.name('pl'+str(i+1)),
        K.Point(
            K.coordinates(
                str(item).strip('[]').replace(' ', '')
                )
        )
    )
)

doc.append(K.Placemark(
    K.name('path'),
    K.LineStyle(
        K.color('#00FFFF'),
        K.width(10)
    ),
    K.LineString(
        K.coordinates(
            ' '.join([str(item).strip('[]').replace(' ', '') for item in line_points])
        )
    )
))

s = etree.tostring(_doc)

print s

这里的 line_points 是一个包含多个列表的列表,里面存的是坐标,格式大概是这样的:

[[-134.15611799999999, 34.783318000000001, 0],
 [-134.713527, 34.435267000000003, 0],
 [-133.726201, 36.646867, 0],
 [-132.383655, 35.598272999999999, 0],
 [-132.48034200000001, 36.876308999999999, 0],
 [-131.489846, 36.565426000000002, 0],...

你可以在这里 (http://sfgeo.org/data/contrib/tiburon.html)看到一个输出的例子,另外在这个jsfiddle上也可以查看:http://jsfiddle.net/bvmou/aTkpN/7/,不过在公开查看时可能会遇到api密钥的问题,建议你在自己的电脑上试试。

撰写回答