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

如何在GMap.Net.WinForms地图路径上显示方向箭头?

在GMap.Net WinForms中为路径添加方向箭头

原代码存在的问题

  1. 角度计算逻辑错误:你用两个点的坐标相加来计算偏移量,这无法得到两点间的方向差,正确做法是用终点坐标减去起点坐标。
  2. Tooltip无法实现旋转:用ToolTipText = ">"的方式不能让箭头随路径方向旋转,因为Tooltip不支持旋转属性,必须使用支持旋转的自定义标记。

正确实现方案

步骤1:创建支持旋转的自定义箭头标记

定义一个继承自GMarkerGoogle的自定义标记类,通过重绘方法实现可旋转的箭头:

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

public class GMarkerArrow : GMarkerGoogle
{
    private float _rotation;
    public float Rotation
    {
        get => _rotation;
        set
        {
            _rotation = value;
            UpdateLocalPosition();
        }
    }

    public GMarkerArrow(PointLatLng pos) : base(pos, GMarkerGoogleType.red)
    {
        Size = new Size(20, 20);
        Offset = new Point(-Size.Width / 2, -Size.Height / 2);
    }

    public override void OnRender(Graphics g)
    {
        // 平移到标记位置后旋转画布
        g.TranslateTransform(LocalPosition.X, LocalPosition.Y);
        g.RotateTransform(Rotation);
        
        // 绘制红色箭头形状
        using (var pen = new Pen(Color.Red, 2))
        using (var brush = new SolidBrush(Color.Red))
        {
            Point[] arrowShape = new[]
            {
                new Point(0, -10),   // 箭头尖端
                new Point(-5, 5),    // 左尾翼
                new Point(0, 0),     // 中间基点
                new Point(5, 5)      // 右尾翼
            };
            g.FillPolygon(brush, arrowShape);
            g.DrawPolygon(pen, arrowShape);
        }
        
        g.ResetTransform();
    }
}

步骤2:计算方向角并添加箭头标记

在循环中计算每段路径的中点和方向角,添加自定义箭头标记:

for (int i = 1; i < mainPoints.Count; i++)
{
    // 计算当前路径段的中点
    double midLat = (mainPoints[i-1].Lat + mainPoints[i].Lat) / 2;
    double midLng = (mainPoints[i-1].Lng + mainPoints[i].Lng) / 2;
    PointLatLng midPoint = new PointLatLng(midLat, midLng);

    // 计算从起点到终点的方向角(正北为0度,顺时针旋转)
    double deltaLng = mainPoints[i].Lng - mainPoints[i-1].Lng;
    double deltaLat = mainPoints[i].Lat - mainPoints[i-1].Lat;
    double radians = Math.Atan2(deltaLng, deltaLat);
    double angle = radians * 180 / Math.PI;

    // 创建箭头标记并设置旋转角度
    GMarkerArrow arrowMarker = new GMarkerArrow(midPoint);
    arrowMarker.Rotation = (float)angle;
    markersLayer.Markers.Add(arrowMarker);
}

gmap.ZoomAndCenterRoute(route);

关键说明

  • 方向角计算:Math.Atan2(deltaLng, deltaLat)用于计算地理方向,转换为角度后直接对应GMap标记的顺时针旋转角度(0度代表正北)。
  • 自定义标记优势:通过重绘方法可以完全控制箭头的样式、大小和颜色,比内置标记更灵活。

内容的提问来源于stack exchange,提问作者Javad-M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:26:27