KMZ生成器部署Azure后远程用户无法显示自定义图标
问题解决:Azure部署后KMZ自定义图标无法显示
核心原因
你代码里创建IconStyle时用了服务器本地的绝对路径作为icon_href,但KMZ是独立的压缩包,Google Earth解析时只会在KMZ内部查找资源,不会去访问服务器的本地路径,所以找不到图标,显示红叉。
解决方案
把IconStyle的icon_href改成图标文件名(相对路径),因为你打包KMZ时已经把图标放在了和KML同目录的位置,用文件名就能正确引用。
修改关键代码
在generate_kml函数中,创建IconStyle的一行需要修改:
原代码:
icon_style = styles.IconStyle(icon_href=icon_path, scale=2.0)
修改为:
# 使用图标文件名作为相对路径,而非服务器绝对路径 icon_style = styles.IconStyle(icon_href=os.path.basename(icon_path), scale=2.0)
完整修改后的generate_kml函数
def generate_kml(institution, city=None, state=None, icon_path=None): print('kml generator initiated') # Update the icon_path if it's not provided if icon_path is None: script_dir = os.path.dirname(os.path.abspath(__file__)) icon_filename = 'Bank Icon.png' icon_path = os.path.join(script_dir, icon_filename) # Determine the location based on the search scope location = f"{city}, {state}" # Search for institution locations within the location search_results = search_institution_locations(institution, location) # Parse the XML search results root = ET.fromstring(search_results) # Create a KML document doc = kml.Document() # 关键修改:使用图标文件名作为相对路径 icon_style = styles.IconStyle(icon_href=os.path.basename(icon_path), scale=2.0) # Create the LabelStyle with a scale of 0.0 to hide the text label_style = styles.LabelStyle(scale=0.0) # Combine the IconStyle and LabelStyle into a Style style = styles.Style(id='icon', styles=[icon_style, label_style]) doc.append_style(style) # Add Placemarks for each search result for result in root.findall("result"): name = result.find("name").text address = result.find("formatted_address").text lat = float(result.find("geometry/location/lat").text) lng = float(result.find("geometry/location/lng").text) placemark = kml.Placemark( name=name, description=address, styleUrl="#icon" # Use the custom icon style ) placemark.geometry = Point((lng, lat)) doc.append(placemark) # Save KML file with tempfile.NamedTemporaryFile(suffix='.kml', delete=False) as temp: print(doc.to_string(prettyprint=True)) kml_file_path = temp.name with open(kml_file_path, "w", encoding="utf-8") as f: f.write('<?xml version="1.0" encoding="UTF-8"?>\n') f.write(doc.to_string(prettyprint=True)) # Create KMZ file kmz_file_name = f"{institution.replace(' ', '_')}_locations.kmz" with tempfile.NamedTemporaryFile(suffix='.kmz', delete=False) as temp: kmz_file_path = temp.name with zipfile.ZipFile(kmz_file_path, 'w', zipfile.ZIP_DEFLATED) as zf: zf.write(kml_file_path, arcname=os.path.splitext(kmz_file_name)[0] + '.kml') zf.write(icon_path, arcname=os.path.basename(icon_path)) # Remove the temporary KML file os.remove(kml_file_path) return kmz_file_path
验证步骤
- 重新部署修改后的代码到Azure
- 生成KMZ文件后解压,查看KML中的
<Icon><href>标签内容,应该是Bank Icon.png而非服务器绝对路径 - 用Google Earth打开KMZ,确认自定义图标正常显示
内容的提问来源于stack exchange,提问作者Kevin Green
相关产品推荐
相关产品推荐

