我刚刚开始使用 gmap.net,我正在寻找在标记下添加标签的功能。我看到有工具提示,但我想在我的标记下有一个带有一个单词描述的常量标签。
我搜索了文档或其他答案,但我找不到任何让我相信它没有实现的东西。如果有人可以验证这一点,我将不胜感激。
您需要创建自己的自定义标记。
基于 GMapMarker 的来源和派生的GMarkerGoogle我想出了这个简化的例子:
public class GmapMarkerWithLabel : GMapMarker, ISerializable
{
private Font font;
private GMarkerGoogle innerMarker;
public string Caption;
public GmapMarkerWithLabel(PointLatLng p, string caption, GMarkerGoogleType type)
: base(p)
{
font = new Font("Arial", 14);
innerMarker = new GMarkerGoogle(p, type);
Caption = caption;
}
public override void OnRender(Graphics g)
{
if (innerMarker != null)
{
innerMarker.OnRender(g);
}
g.DrawString(Caption, font, Brushes.Black, new PointF(0.0f, innerMarker.Size.Height));
}
public override void Dispose()
{
if(innerMarker != null)
{
innerMarker.Dispose();
innerMarker = null;
}
base.Dispose();
}
#region ISerializable Members
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
protected GmapMarkerWithLabel(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
}
用法(假设一个GMap
名为 的实例gm
):
GMapOverlay markerOverlay = new GMapOverlay("markers");
gm.Overlays.Add(markerOverlay);
var labelMarker = new GmapMarkerWithLabel(new PointLatLng(53.3, 9), "caption text", GMarkerGoogleType.blue);
markerOverlay.Markers.Add(labelMarker)
我将在这里回答,因为这是在寻找显示WPF GMAP.NET 库的文本标记时弹出的第一个问题。使用库的 WPF 版本显示文本标记实际上比在 WinForms 中容易得多,或者至少比接受的答案要容易得多。
GMapMarker
WPF 中有一个typeShape
属性UIElement
,这意味着您可以提供一个System.Windows.Controls.TextBlock
对象来显示文本标记:
Markers.Add(new GMapMarker(new PointLatLng(latitude, longitude))
{
Shape = new System.Windows.Controls.TextBlock(new System.Windows.Documents.Run("Label"))
});
由于标记在给定位置显示形状的左上部分,因此您可以使用该GMapMarker.Offset
属性来根据其尺寸调整文本位置。例如,如果您希望文本水平居中于标记的位置:
var textBlock = new TextBlock(new Run("Label"));
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
textBlock.Arrange(new Rect(textBlock.DesiredSize));
Markers.Add(new GMapMarker(new PointLatLng(request.Latitude, request.Longitude))
{
Offset = new Point(-textBlock.ActualWidth / 2, 0),
Shape = textBlock
});
得到TextBlock
' 尺寸的解决方案很快就从这个问题中得到了,所以如果你需要一种更准确的方法来让块的尺寸与偏移一起玩,我建议你从那里开始。