在simplekml中显示本地图像

6 投票
1 回答
3899 浏览
提问于 2025-04-17 18:52

我正在尝试使用simplekml把一堆带地理标签的照片放进一个KML文件(实际上是KMZ文件),这样我就可以在谷歌地球中查看它们。我已经成功显示了位置,但是当我试图把图片放进“描述”里,以便点击位置时能显示图片,却不成功。结果只是一个空白的图片。我是通过使用这里展示的addfile()命令来做的。我的代码看起来是这样的:

import os, simplekml

path = r'C:\Users\as\Desktop\testpics'                     
    
kml = simplekml.Kml()

for (dirpath, dirnames, filenames) in os.walk(path):
    for filename in filenames:
        fullpath = os.path.join(dirpath, filename)
        try:
            Lat, Long, Alt = GetLatLong(fullpath) #Didn't include this function, but it appears to work
        except:
            Lat, Long, Alt = (None, None, None)
        if Lat: #Only adds to kml if it has Lat value.
            x, y = (FormatLatLong(Lat), FormatLatLong(Long)) #puts into decimal coords
            point = kml.newpoint(name = filename , coords = [(y,x)])
            picpath = kml.addfile(fullpath)
            point.description = '<img src="' + picpath +'" alt="picture" width="400" height="300" align="left" />'

            

kml.savekmz("kmltest2.kmz", format = False)

如你所见,我基本上是直接复制粘贴了上面页面关于“addfile”的使用说明。point.description这一行似乎是出问题的地方。

图片确实被添加到了kmz压缩包里,但在位置气泡中没有显示出来。我想这可能是因为我在Windows 7上操作,斜杠方向不对,但我尝试手动把files\image.jpg改成files/image.jpg,结果也没解决问题。生成的KMZ文档.doc.kml文件看起来是这样的:

    <kml xmlns="http://www.opengis.net/kml/2.2"xmlns:gx="http://www.google.com/kml/ext/2.2">
    <Document id="feat_1">
    <Placemark id="feat_2">
    <name>DSC00001.JPG</name>
    <description>&lt;img src="files/DSC00001.JPG" alt="picture" width="400" height="300" align="left" /&gt;</description>
    <Point id="geom_0"><coordinates>18.9431816667,9.44355222222,0.0</coordinates>
    </Point></Document></kml>

(我只保留了一个点)非常感谢,
亚历克斯

1 个回答

3

可能是因为你写的kml文件中有一个未关闭的标记标签。你需要在点标签结束后,关闭这个标记标签。

<kml xmlns="http://www.opengis.net/kml/2.2"xmlns:gx="http://www.google.com/kml/ext/2.2">
    <Document id="feat_1">
    <Placemark id="feat_2">
    <name>DSC00001.JPG</name>
    <description>&lt;img src="files/DSC00001.JPG" alt="picture" width="400" height="300" align="left" /&gt;</description>
    <Point id="geom_0"><coordinates>18.9431816667,9.44355222222,0.0</coordinates>
    </Point></Placemark></Document></kml>

如果在放置标记标签后,上面的代码不管用,那就试试用气泡样式代替描述标签,下面的代码可以试试。

<kml xmlns="http://www.opengis.net/kml/2.2"
     xmlns:gx="http://www.google.com/kml/ext/2.2" 
     xmlns:kml="http://www.opengis.net/kml/2.2" 
     xmlns:atom="http://www.w3.org/2005/Atom"
>
<Document id="feat_1">
<Placemark id="feat_2">
<name>DSC00001.JPG</name>
<Style>
<BalloonStyle>
<text><![CDATA[
 <table width=100% cellpadding=0 cellspacing=0>
  <tr><td><img width=100% src='files/DSC00001.jpg' /></td></tr></table>]]>
</text>
</BalloonStyle>
</Style> 
<Point id="geom_0">
<coordinates>18.9431816667,9.44355222222</coordinates>
</Point>
</Placemark>
</Document>
</kml>

撰写回答