You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Python 3.7与Windows 10环境下使用Matplotlib绘制KML文件数据的问题咨询

解决NetworkLink类型KML的解析与matplotlib/cartopy绘制问题

Hey there, let's break down why your code is throwing that IndexError and walk through a better way to plot those territorial seas boundaries with matplotlib and cartopy.

Why is features an empty list?

Your original KML file is a NetworkLink, not a file containing actual geographic geometry data. Here's what that means:

  • The KML you downloaded only contains a pointer to a remote KML resource (http://geo.vliz.be/geoserver/gwc/service/kml/MarineRegions:eez_12nm.png.kml), not the polygon shapes of the 12NM territorial seas.
  • fastkml parses exactly what's in your local file—it doesn't automatically fetch the remote KML linked in the NetworkLink tag. Since your local file has no Document or Placemark elements (the ones that hold geometry data), features = list(k.features()) ends up as an empty list.

Better Solutions to Plot the Territorial Seas

The NetworkLink points to a tile-based KML (for Google Earth to load map tiles), which isn't useful for vector plotting with matplotlib. Instead, let's use the actual vector data from MarineRegions directly.

Option 1: Use Shapefile (Most Reliable)

MarineRegions provides the 12NM territorial seas as a Shapefile, which is much easier to work with in Python. Here's how to plot it:

  1. Download the Shapefile from MarineRegions (under the Maritime Boundaries Geodatabase: Territorial Seas (12NM) resource)
  2. Use geopandas and cartopy to plot it:
import geopandas as gpd
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Load the downloaded Shapefile
gdf = gpd.read_file("path/to/eez_12nm.shp")

# Set up the plot with cartopy
fig, ax = plt.subplots(figsize=(14, 10), subplot_kw={"projection": ccrs.PlateCarree()})

# Plot the territorial seas
gdf.plot(
    ax=ax,
    edgecolor="navy",
    facecolor="lightblue",
    alpha=0.4,
    linewidth=0.5
)

# Add map details
ax.coastlines(resolution="10m", color="black", linewidth=0.8)
ax.gridlines(draw_labels=True, linestyle="--", alpha=0.7)

plt.title("Global 12NM Territorial Seas", fontsize=16)
plt.show()

Option 2: Parse a Vector KML (If You Prefer KML)

If you want to stick with KML, make sure you download the vector KML version of the data (not the tile-based NetworkLink one). Then use fastkml to extract geometries and plot:

from fastkml import kml
import shapely.geometry as sg
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

# Load and parse the vector KML
filename = "path/to/vector_territorial_seas.kml"
with open(filename, 'rb') as kml_file:
    kml_content = kml_file.read()

k = kml.KML()
k.from_string(kml_content)

# Extract all geometry features from the KML
geometries = []
for doc in k.features():
    for placemark in doc.features():
        if placemark.geometry is not None:
            geometries.append(placemark.geometry)

# Plot with cartopy
fig, ax = plt.subplots(figsize=(14, 10), subplot_kw={"projection": ccrs.PlateCarree()})

for geom in geometries:
    # Handle single polygons and multi-polygons
    if isinstance(geom, sg.Polygon):
        ax.add_geometries(
            [geom],
            crs=ccrs.PlateCarree(),
            edgecolor="navy",
            facecolor="lightblue",
            alpha=0.4
        )
    elif isinstance(geom, sg.MultiPolygon):
        ax.add_geometries(
            geom.geoms,
            crs=ccrs.PlateCarree(),
            edgecolor="navy",
            facecolor="lightblue",
            alpha=0.4
        )

ax.coastlines(resolution="10m", color="black")
ax.gridlines(draw_labels=True, linestyle="--")
plt.title("Global 12NM Territorial Seas", fontsize=16)
plt.show()

内容的提问来源于stack exchange,提问作者Lilly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:23:09