转载:http://www.cnblogs.com/wuhuacong/archive/2010/03/10/1681382.html
在网上搞了好多天都没搞明白这玩意儿是怎么用,我服了,决定放弃。
今天用它的例子,改成我需要的。
截止到今天2011-01-20所有问题解决。
贴出前人的劳动成果:
我们先看看GMap.NET的定义:
GMap.NET是一个强大、免费、跨平台、开源的.NET控件,它在Windows Forms 和WPF环境中能够通过Google, Yahoo!, Bing, OpenStreetMap, ArcGIS, Pergo, SigPac等实现寻找路径、地理编码以及地图展示功能,并支持缓存和运行在Mobile环境中。
GMap.NET是一个开源的GEO地图定位和跟踪程序。就像谷歌地图、雅虎地图一样,可以自动计算两地的距离,定位经纬度,与Google地图不同的是,该项目是建立在C#语言WinForm基础上的。可以对地图放大缩小,进行城市标记等。
GMap.NET的项目地址是http://greatmaps.codeplex.com/ ,我们可以下载相关的例子和源码进行学习和研究。我在Google上搜过相关的项目,好像介绍的文章不多,不过不影响这个控件的强大和易用。我们先看看它的界面截图:
GMap.NET号称是可以支持很多种地图来源的,不过我试了一下,好像有部分是有些问题,最好的效果是GoogleMapChina,如上图所示。
我用GoogleMapChina可以放大到很详细的街道图,做了一个地址查询的例子,如下所示:
控件可以绘出两地的行车线路或者步行线路等,而且能够算出两地的距离,不过对于地理编码的解析好像不是很准确,也获取不到公交线路等信息,不过应付一般的应用,应该是蛮不错的了。
这个控件默认使用了右键按住作为拖动,和GoogleMap用鼠标左键作为拖动有点不太一样(不过可以通过this.gMapControl1.DragButton = MouseButtons.Left;来实现左键拖动),两者皆能够支持滚轮放大缩小的操作。控件还支持经纬度的精确定位,绘制图标(支持绿色、红色的图标、十字符号等标记),支持中心点移动 ,导出地图图片等功能。由于地图控件支持路线的绘制,所以应该支持一般的GIS应用中的轨迹回放功能的。由于地图控件支持鼠标位置和经纬度坐标的转换功能,因此,可以随意获取到相关的经纬度信息。
这个Winform的地图控件,虽然对比Web的GoogleMap来说,很多功能还不具备,但是较普通的MapX和MapXtreme或者ArcGis等传统的GIS来说,不用付太多的费用(甚至不用付费用),就可以使用上精细的地图,不得不说是一个好消息。
其实目前GMap.NET提供的功能还不是很多,因此其演示的例子基本上都涉及到了,我在此基础上做了一些改进和运用,总结下功能代码吧。
首先使用控件前,需要初始化一些变量和事件,初始化代码如下所示:
代码
其中的OnMarkerClick好像虽然有相关的事件,但是并不能捕获单击图标的时间操作,估计是没有完成该功能吧。
GMap.NET提供了各种鼠标的操作事件,我们重载即可实现特殊的控制处理了:
鼠标事件操作
void gMapControl1_DoubleClick(object sender, EventArgs e)
{
this.gMapControl1.Zoom +=
1;
this.gMapControl1.CurrentPosition = lastPosition;
}
void gMapControl1_MouseMove(object sender, MouseEventArgs e)
{
PointLatLng latLng =
this.gMapControl1.FromLocalToLatLng(e.X, e.Y);
this.tsslPosition.Text =
string.Format("经度:{0}, 纬度:{1} ", latLng.Lng, latLng.Lat);
}
private
void MainMap_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.isMouseDown =
true;
lastPosition =
this.gMapControl1.FromLocalToLatLng(e.X, e.Y);
}
}
private
void MainMap_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
this.isMouseDown =
false;
}
}
保存截图的操作如下所示
代码
private
void tsbSavePicture_Click(object sender, EventArgs e)
{
try
{
using (SaveFileDialog dialog =
new SaveFileDialog())
{
dialog.Filter =
"PNG (*.png)|*.png";
dialog.FileName =
"GMap.NET image";
Image image =
this.gMapControl1.ToImage();
if (image !=
null)
{
using (image)
{
if (dialog.ShowDialog() == DialogResult.OK)
{
string fileName = dialog.FileName;
if (!fileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
{
fileName +=
".png";
}
image.Save(fileName);
MessageBox.Show("图片已保存: "
+ dialog.FileName, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
}
}
catch (Exception exception)
{
MessageBox.Show("图片保存失败: "
+ exception.Message, "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
地址查询并绘制图标的代码如下:
代码private
void btnSearch_Click(object sender, EventArgs e)
{
if (this.txtAddress.Text.Length ==
0)
{
this.txtAddress.Focus();
MessageBox.Show("请输入查询的地址");
}
string search =
string.Format("{0},{1}", this.txtCity.Text, this.txtAddress.Text);
GeoCoderStatusCode code =
this.gMapControl1.SetCurrentPositionByKeywords(search);
if (code != GeoCoderStatusCode.G_GEO_SUCCESS)
{
MessageBox.Show("地址没有找到:'"
+
this.txtAddress.Text +
"', 原因:"
+ code.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
this.objects.Markers.Clear();
AddLocation(this.txtAddress.Text);
}
private
void AddLocation(string place)
{
GeoCoderStatusCode unknow = GeoCoderStatusCode.Unknow;
PointLatLng? latLngFromGeocoder = Singleton<GMaps>.Instance.GetLatLngFromGeocoder(place, out unknow);
if (latLngFromGeocoder.HasValue && (unknow == GeoCoderStatusCode.G_GEO_SUCCESS))
{
GMapMarker item =
new GMapMarkerGoogleGreen(latLngFromGeocoder.Value);
GMapMarkerRect rect =
new GMapMarkerRect(latLngFromGeocoder.Value);
rect.Size =
new System.Drawing.Size(100, 100);
rect.ToolTipText = place;
rect.TooltipMode = MarkerTooltipMode.Always;
this.objects.Markers.Add(item);
this.objects.Markers.Add(rect);
}
}
绘制两地之间的线路图命令如下所示:
代码
private
void ctxMenu_GetRout_Click(object sender, EventArgs e)
{
this.objects.Markers.Clear();
this.routes.Routes.Clear();//清楚路线
this.start = defaultLocation;
this.end =
this.gMapControl1.FromLocalToLatLng(this.contextMenuStrip1.Bounds.X, this.contextMenuStrip1.Bounds.Y);
MapRoute route = Singleton<GMaps>.Instance.GetRouteBetweenPoints(this.start, this.end, false, (int)this.gMapControl1.Zoom);
if (route !=
null)
{
GMapRoute item =
new GMapRoute(route.Points, route.Name);
item.Color = Color.Blue;
this.routes.Routes.Add(item);
GMapMarker marker =
new GMapMarkerGoogleRed(this.start);
//marker.ToolTipText = "Start: " + route.Name;
marker.TooltipMode = MarkerTooltipMode.Always;
//Placemark place = this.gMapControl1.Manager.GetPlacemarkFromGeocoder(this.end);//地标不准确,不用
MapRoute mapRoute =
this.gMapControl1.Manager.GetRouteBetweenPoints(this.start, this.end, true, (int)this.gMapControl1.Zoom);
GMapMarker marker2 =
new GMapMarkerGoogleGreen(this.end);
marker2.ToolTipText =
string.Format("目的地距离:{0}公里 ", Math.Round(mapRoute.Distance, 2));
marker2.TooltipMode = MarkerTooltipMode.Always;
this.objects.Markers.Add(marker);
this.objects.Markers.Add(marker2);
this.gMapControl1.ZoomAndCenterRoute(item);
}
}
放大、缩小、重新加载地图的操作如下:
代码
private
void ctxMenu_ZoomOut_Click(object sender, EventArgs e)
{
this.gMapControl1.Zoom +=
1;
}
private
void ctxMenu_ZoomIn_Click(object sender, EventArgs e)
{
this.gMapControl1.Zoom -=
1;
}
private
void tsbReload_Click(object sender, EventArgs e)
{
this.gMapControl1.ReloadMap();
}
程序截图如下所示:
这是一个基于Winform的地图控件。该地图控件的定义如下:
GMap.NET是一个强大、免费、跨平台、开源的.NET控件,它在Windows Forms 和WPF环境中能够通过Google, Yahoo!, Bing, OpenStreetMap, ArcGIS, Pergo, SigPac等实现寻找路径、地理编码以及地图展示功能,并支持缓存和运行在Mobile环境中。
GMap.NET是一个开源的GEO地图定位和跟踪程序。就像谷歌地图、雅虎地图一样,可以自动计算两地的距离,定位经纬度,与Google地图不同的是,该项目是建立在C#语言WinForm基础上的。可以对地图放大缩小,进行城市标记等。
本文主要介绍应用该控件来批量解析地址经纬度坐标。由于项目需要,我需要把数据库里面的4千多条地址信息解析出经纬度坐标,以供其他用途。经纬度坐标不要求非常精确,大体位置准确即可。如果人工通过Googlemap或者其他途径标准,工作量非常大,而且也很枯燥。由于之前接触过该控件,知道好像比较容易能够解析获取地址的经纬度坐标,那么我们把数据库信息逐一解析即可,这样可以节省人力,更重要的是,可以避免做枯燥的工作。我们先看看程序的运行效果,然后分析如何具体编码实现。
开始一段时间的效果图:
基本完成的效果图:
代码实现如下所示,主要利用了背景工作线程BackgroundWorker来提高界面的友好响应。
private BackgroundWorker work =
new BackgroundWorker();
public FrmMainMap()
{
InitializeComponent();
work.WorkerReportsProgress =
true;
work.DoWork +=
new DoWorkEventHandler(work_DoWork);
work.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(work_RunWorkerCompleted);
work.ProgressChanged +=
new ProgressChangedEventHandler(work_ProgressChanged);
}
void work_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar.Value = e.ProgressPercentage;
this.tsslTips.Text = e.UserState.ToString();
}
private
void FrmMainMap_FormClosing(object sender, FormClosingEventArgs e)
{
work.DoWork -=
new DoWorkEventHandler(work_DoWork);
work.RunWorkerCompleted -=
new RunWorkerCompletedEventHandler(work_RunWorkerCompleted);
}
void work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
string tips =
string.Format("更新完成, 共成功更新数据 {0} 个", e.Result);
this.tsslTips.Text = tips;
this.progressBar.Value =
100;
MessageUtil.ShowTips(tips);
}
void work_DoWork(object sender, DoWorkEventArgs e)
{
string sql =
"select t.ID, t.company_addr from tbpark_enterprise t where t.company_addr is not null and t.latitude is null ";
Database db = DatabaseFactory.CreateDatabase();
DbCommand command = db.GetSqlStringCommand(sql);
Dictionary<int, string> addrList =
new Dictionary<int, string>();
using (IDataReader dr = db.ExecuteReader(command))
{
SmartDataReader reader =
new SmartDataReader(dr);
while (reader.Read())
{
int id = reader.GetInt32("ID");
string addr = reader.GetString("company_addr");
work.ReportProgress(10, string.Format("正在处理地址[ {0} ]", addr));
if (!string.IsNullOrEmpty(addr))
{
int sindex = addr.IndexOfAny(new
char[] { '(', '(' });
if (sindex >
0)
{
addr = addr.Substring(0, sindex);
}
if (!addrList.ContainsKey(id))
{
addrList.Add(id, addr);
}
}
}
}
work.ReportProgress(20, string.Format("获取列表地址信息结束,正在获取Google地图坐标..."));
int totoal = addrList.Count;
double step = Convert.ToDouble(100) / totoal;
int i =
1;
int successCount =
0;
foreach (int id in addrList.Keys)
{
int percent = Convert.ToInt32(step * i);
work.ReportProgress(percent, string.Format("正在获取Google地图坐标...,已成功获取 {0} 个", successCount));
try
{
string addr = addrList[id];
GeoCoderStatusCode unknow = GeoCoderStatusCode.Unknow;
PointLatLng? latLngFromGeocoder = Singleton<GMaps>.Instance.GetLatLngFromGeocoder(addr, out unknow);
if (latLngFromGeocoder.HasValue && (unknow == GeoCoderStatusCode.G_GEO_SUCCESS))
{
PointLatLng latLng = latLngFromGeocoder.Value;
sql =
string.Format("Update tbpark_enterprise t set t.LATITUDE={0}, t.LONGITUDE={1} where t.ID={2}",
latLng.Lat, latLng.Lng, id);
command = db.GetSqlStringCommand(sql);
bool success = db.ExecuteNonQuery(command) >
0;
if (success)
{
successCount++;
}
}
else
{
LogHelper.Info(unknow.ToString());
}
}
catch (Exception ex)
{
LogHelper.Error(ex);
}
i++;
}
e.Result = successCount;
}
上面最为关键的部分代码就是如何解析地址为坐标的操作,判断如果解析成功,则获取相应的地理坐标即可,是下面这段:
string addr = addrList[id];
GeoCoderStatusCode unknow = GeoCoderStatusCode.Unknow;
PointLatLng? latLngFromGeocoder = Singleton<GMaps>.Instance.GetLatLngFromGeocoder(addr, out unknow);
if (latLngFromGeocoder.HasValue && (unknow == GeoCoderStatusCode.G_GEO_SUCCESS))
{
PointLatLng latLng = latLngFromGeocoder.Value;
sql =
string.Format("Update tbpark_enterprise t set t.LATITUDE={0}, t.LONGITUDE={1} where t.ID={2}",
latLng.Lat, latLng.Lng, id);
command = db.GetSqlStringCommand(sql);
bool success = db.ExecuteNonQuery(command) >
0;
if (success)
{
successCount++;
}
}
this .gMapControl1.Manager.Mode = AccessMode.ServerAndCache;
this .gMapControl1.MapType = MapType.GoogleMapChina;
this .gMapControl1.MaxZoom = 18 ;
this .gMapControl1.MinZoom = 8 ;
this .gMapControl1.Zoom = 13 ;
this .gMapControl1.MouseMove += new MouseEventHandler(gMapControl1_MouseMove);
this .gMapControl1.DoubleClick += new EventHandler(gMapControl1_DoubleClick);
this .gMapControl1.MouseDown += new MouseEventHandler(gMapControl1_MouseDown);
this .gMapControl1.MouseUp += new MouseEventHandler(gMapControl1_MouseUp);
this .gMapControl1.OnCurrentPositionChanged += new CurrentPositionChanged(gMapControl1_OnCurrentPositionChanged);
this .gMapControl1.OnTileLoadStart += new TileLoadStart(gMapControl1_OnTileLoadStart);
this .gMapControl1.OnTileLoadComplete += new TileLoadComplete(gMapControl1_OnTileLoadComplete);
this .gMapControl1.OnMarkerClick += new GMap.NET.WindowsForms.MarkerClick(gMapControl1_OnMarkerClick);
this .gMapControl1.OnMapZoomChanged += new MapZoomChanged(gMapControl1_OnMapZoomChanged);
this .gMapControl1.OnMapTypeChanged += new MapTypeChanged(gMapControl1_OnMapTypeChanged);
this .routes = new GMapOverlay( this .gMapControl1, " routes " );
this .gMapControl1.Overlays.Add( this .routes);
this .objects = new GMapOverlay( this .gMapControl1, " objects " );
this .gMapControl1.Overlays.Add( this .objects);
this .top = new GMapOverlay( this .gMapControl1, " top " );
this .gMapControl1.Overlays.Add( this .top);
this .currentMarker = new GMapMarkerGoogleRed( this .gMapControl1.CurrentPosition);
this .top.Markers.Add( this .currentMarker);
this .center = new GMapMarkerCross( this .gMapControl1.CurrentPosition);
this .top.Markers.Add( this .center);
this .myShop = new GMapOverlay( this .gMapControl1, " myShop " );
this .gMapControl1.Overlays.Add( this .myShop);
DisplayMyShop();
SetZoomCenter();
this .gMapControl1.DragButton = MouseButtons.Left;
}
void gMapControl1_OnMapTypeChanged(MapType type)
{
throw new NotImplementedException();
}
void gMapControl1_OnMapZoomChanged()
{
throw new NotImplementedException();
}
void gMapControl1_OnMarkerClick(GMap.NET.WindowsForms.GMapMarker item, MouseEventArgs e)
{
throw new NotImplementedException();
}
void gMapControl1_OnTileLoadComplete( long ElapsedMilliseconds)
{
throw new NotImplementedException();
}
void gMapControl1_OnCurrentPositionChanged(PointLatLng point)
{
throw new NotImplementedException();
}
void gMapControl1_OnTileLoadStart()
{
throw new NotImplementedException();
}
void gMapControl1_MouseUp( object sender, MouseEventArgs e)
{
throw new NotImplementedException();
}
void gMapControl1_MouseDown( object sender, MouseEventArgs e)
{
throw new NotImplementedException();
}
void gMapControl1_DoubleClick( object sender, EventArgs e)
{
throw new NotImplementedException();
}
void gMapControl1_MouseMove( object sender, MouseEventArgs e)
{
throw new NotImplementedException();
}