GMap.NET 是 .NET 生態最成熟的開源地圖控件庫,支援 Google、Bing、OpenStreetMap、ArcGIS 等十幾家提供者,兼容 WinForms、WPF、Mobile。本文從專案建立、核心 DLL 參考、控件封裝、地圖初始化、標記互動完整演示雙平台整合。
greatmaps_81b71bf30091GMap.NET.Core (核心邏輯)GMap.NET.WindowsForms (WinForms 控件)GMap.NET.WindowsPresentation (WPF 控件)public partial class MapControl : GMap.NET.WindowsForms.GMapControl {
public MapControl() { InitializeComponent(); }
}
建置後工具箱自動出現 MapControl,拖入 Form 即可。
public partial class MainForm : Form {
public MainForm() {
InitializeComponent();
InitMap();
}
private void InitMap() {
// 離線模式檢測
try { System.Net.Dns.GetHostEntry("www.google.com.hk"); }
catch { mapControl.Manager.Mode = AccessMode.CacheOnly; }
mapControl.MapProvider = GMap.NET.MapProviders.GMapProviders.GoogleChinaMap;
mapControl.MinZoom = 2;
mapControl.MaxZoom = 17;
mapControl.Zoom = 5;
mapControl.ShowCenter = false; // 隱藏中心十字
mapControl.DragButton = MouseButtons.Left;
mapControl.Position = new PointLatLng(32.064, 118.704); // 南京
mapControl.OnMapZoomChanged += MapControl_OnMapZoomChanged;
mapControl.MouseClick += MapControl_MouseClick;
}
private void MapControl_MouseClick(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
PointLatLng pt = mapControl.FromLocalToLatLng(e.X, e.Y);
GMap.NET.WindowsForms.GMapMarker marker = new GMap.NET.WindowsForms.Markers.GMarkerGoogle(pt, GMarkerGoogleType.red_dot);
mapControl.Overlays.Add(new GMap.NET.WindowsForms.GMapOverlay("markers") { Markers = { marker } });
}
}
}
public class MapControl : GMap.NET.WindowsPresentation.GMapControl { }
<Window x:Class="GMapWPFDemo.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:GMapWPFDemo"
Title="MainWindow" Height="410" Width="618">
<Grid>
<GroupBox Name="mapgroup">
<src:MapControl x:Name="mapControl" Zoom="13" MaxZoom="24" MinZoom="1" />
</GroupBox>
</Grid>
</Window>
mapControl.MapProvider = GMapProviders.GoogleChinaMap;
mapControl.MinZoom = 2; mapControl.MaxZoom = 17; mapControl.Zoom = 5;
mapControl.ShowCenter = false;
mapControl.DragButton = MouseButton.Left;
mapControl.Position = new PointLatLng(32.064, 118.704);
mapControl.MouseLeftButtonDown += (s, e) => {
Point click = e.GetPosition(mapControl);
PointLatLng pt = mapControl.FromLocalToLatLng((int)click.X, (int)click.Y);
var marker = new GMap.NET.WindowsPresentation.GMapMarker(pt);
mapControl.Markers.Add(marker);
};
| 特性 | WinForms | WPF |
|---|---|---|
| 圖層管理 | GMapOverlay 容器,再加 Markers | 無 Overlay 概念,Markers 直接加在控件 |
| Marker 建立 | 用 GMarkerGoogle 內建圖示或自訂 Bitmap | 直接 new GMapMarker(point),需自訂視覺模板 |
| 事件模型 | WinForms 事件 (MouseClick) | RoutedEvent (MouseLeftButtonDown) |
| 效能/記憶體 | GDI+ 繪圖,大量 Marker 易卡頓 | WPF 保留模式,GPU 加速,大數據表現較好 |
GMaps.Instance.Mode = AccessMode.CacheOnly + CacheLocation,搭配 MapType 下載瓦片 (需遵守提供者授權)。DataTemplate 含 Ellipse、TextBlock、Image,綁定 Marker.Shape。GMapRoute、GMapPolygon 同樣加入 Overlays/Markers 集合。