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

基于Visual Studio与GMaps.NET的KML导入导出及地图展示求助

嘿,我来帮你搞定导出KML和在GMaps.NET地图上展示KML这两个功能!下面是具体的实现步骤和代码示例,适配你已有的项目:

步骤2:将列表导出为KML文件

KML本质是XML格式的文件,我们可以用.NET自带的XmlWriter来规范生成,避免手动拼接字符串出错。假设你的列表里的实体类是这样的(你可以根据自己的实际属性调整):

public class LocationItem
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

接下来写导出方法,传入你的列表和保存路径即可:

using System.Xml;
using System.Collections.Generic;

public void ExportToKml(List<LocationItem> items, string savePath)
{
    using (XmlWriter writer = XmlWriter.Create(savePath, new XmlWriterSettings { Indent = true }))
    {
        // 写入KML根元素
        writer.WriteStartDocument();
        writer.WriteStartElement("kml", "http://www.opengis.net/kml/2.2");
        writer.WriteStartElement("Document");

        // 遍历列表中的每个项,生成Placemark
        foreach (var item in items)
        {
            writer.WriteStartElement("Placemark");
            
            // 写入名称和描述
            writer.WriteElementString("name", item.Name);
            writer.WriteElementString("description", item.Description);
            
            // 写入坐标点(KML格式是 经度,纬度,海拔)
            writer.WriteStartElement("Point");
            writer.WriteElementString("coordinates", $"{item.Longitude},{item.Latitude},0");
            writer.WriteEndElement(); // 关闭Point
            
            writer.WriteEndElement(); // 关闭Placemark
        }

        writer.WriteEndElement(); // 关闭Document
        writer.WriteEndElement(); // 关闭kml
        writer.WriteEndDocument();
    }
}

调用的时候就像这样(比如点击导出按钮时触发):

private void btnExportKml_Click(object sender, EventArgs e)
{
    // 替换成你自己维护的数据源列表
    var locationList = yourExistingLocationList;
    using (SaveFileDialog sfd = new SaveFileDialog())
    {
        sfd.Filter = "KML文件 (*.kml)|*.kml";
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            ExportToKml(locationList, sfd.FileName);
            MessageBox.Show("KML导出成功!");
        }
    }
}
步骤3:上传KML文件并在GMaps.NET地图中展示

GMaps.NET没有内置的KML解析器,所以我们需要自己解析KML文件里的坐标点,然后添加到地图上。这里用XmlDocument来解析,要注意KML的坐标格式是经度,纬度,海拔,而GMaps.NET的PointLatLng是纬度,经度,需要调换顺序。

先写解析KML的方法:

using System.Xml;
using GMap.NET;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;

public List<PointLatLng> ParseKmlFile(string filePath)
{
    List<PointLatLng> locations = new List<PointLatLng>();
    XmlDocument doc = new XmlDocument();
    doc.Load(filePath);

    // 定义KML的命名空间,避免找不到节点
    XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
    nsMgr.AddNamespace("kml", "http://www.opengis.net/kml/2.2");

    // 获取所有Placemark节点
    XmlNodeList placemarks = doc.SelectNodes("//kml:Placemark", nsMgr);
    foreach (XmlNode pm in placemarks)
    {
        // 获取坐标节点
        XmlNode coordNode = pm.SelectSingleNode(".//kml:coordinates", nsMgr);
        if (coordNode != null && !string.IsNullOrEmpty(coordNode.InnerText))
        {
            // 分割坐标字符串,KML格式是"lon,lat,alt"
            string[] coordParts = coordNode.InnerText.Trim().Split(',');
            if (coordParts.Length >= 2)
            {
                if (double.TryParse(coordParts[1], out double lat) && double.TryParse(coordParts[0], out double lon))
                {
                    locations.Add(new PointLatLng(lat, lon));
                }
            }
        }
    }
    return locations;
}

然后写导入并展示的方法(比如点击导入按钮时触发):

private void btnImportKml_Click(object sender, EventArgs e)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        ofd.Filter = "KML文件 (*.kml)|*.kml";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            // 解析KML获取坐标
            var locations = ParseKmlFile(ofd.FileName);
            
            // 清空地图上已有的标记
            gMapControl1.Markers.Clear();
            
            // 添加新标记到地图
            foreach (var loc in locations)
            {
                GMarkerGoogle marker = new GMarkerGoogle(loc, GMarkerGoogleType.blue);
                // 给标记添加鼠标悬浮提示
                marker.ToolTipMode = MarkerTooltipMode.OnMouseOver;
                marker.ToolTipText = $"坐标:{loc.Lat:F6}, {loc.Lng:F6}";
                gMapControl1.Markers.Add(marker);
            }
            
            // 让地图自动缩放适配所有标记
            if (locations.Count > 0)
            {
                gMapControl1.ZoomAndCenterMarkers(null);
            }
            
            MessageBox.Show("KML导入并展示成功!");
        }
    }
}

一些注意事项

  • 确保你已经在项目中通过NuGet安装了GMaps.NET.WindowsForms包
  • 初始化GMapControl时要设置好地图提供者,比如:
gMapControl1.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
  • 如果你的KML里有更复杂的元素(比如多边形、折线),可以扩展解析逻辑,上面的示例只处理了最基础的点标记。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:46:24