10种常规
设置图层可选状态
///<summary>
///改变层的可选择状态
///</summary>
///<paramname="selectableStatus"></param>
///<returns></returns>
publicboolLayerSelectableStatusUpdate(stringtableAlias,bool selectableStatus)
{
if(mapControl1.Map.Layers[tableAlias]==null)
returnfalse;
MapInfo.Mapping.LayerHelper.SetSelectable(mapControl1.Map.Layers[tableAlias],selectableStatus);
returntrue;
}
设置层的可用状态
///<summary>
///改变层的可用状态为status
///</summary>
///<paramname="layerName"></param>
///<paramname="status"></param>
publicvoidLayerEnableStatusUpdate(stringlayerName,bool status)
{
if(mapControl1.Map.Layers[layerName]!=null&& mapControl1.Map.Layers[layerName].Enabled!=status)
{
mapControl1.Map.Layers[layerName].Enabled=status;
}
}
层居中,看全图
///<summary>
///使指定层全部呈现在地图的可见范围中
///</summary>
///<paramname="tableAlias">层别名</param>
publicvoidLayerCenter(string layerName)
{
MapInfo.Data.Table[] tables=newMapInfo.Data.Table[1];
tables[0] =MapInfo.Engine.Session.Current.Catalog.GetTable(layerName);
if(tables[0]==null)
return;
if(mapControl1.Map.Layers[layerName]==null)
return;
if(mapControl1.Map.Layers[layerName].Enabled== false)
mapControl1.Map.Layers[layerName].Enabled = true;
MapInfo.Mapping.IMapLayerFilteriMapLayerFilter = MapInfo.Mapping.MapLayerFilterFactory.FilterByTable(tables);
MapInfo.Mapping.MapLayerEnumerator mapLayerEnumerator= mapControl1.Map.Layers.GetMapLayerEnumerator(iMapLayerFilter);
mapControl1.Map.SetView(mapLayerEnumerator);
OnFeatureUnclick();
}
放大缩小地图
///<summary>
///放大地图
///</summary>
///<paramname="times">放大倍数,有效值1-10</param>
publicvoidZoomIn(uinttimes)
{
if(times<1|| times>10) return;
MapInfo.Geometry.Distance previousZoom=this.mapControl1.Map.Zoom;
mapControl1.Map.Zoom=newMapInfo.Geometry.Distance(previousZoom.Value/(2*times),previousZoom.Unit);
}
///<summary>
///缩小地图
///</summary>
///<paramname="times">缩小倍数,有效值1-10</param>
publicvoidZoomOut(uinttimes)
{
if(times<1|| times>10) return;
MapInfo.Geometry.Distance previousZoom=this.mapControl1.Map.Zoom;
mapControl1.Map.Zoom=newMapInfo.Geometry.Distance(previousZoom.Value*(2*times),previousZoom.Unit);
}
移动层的顺序
mapControl1.Map.Layers.Move(index1,index2);
图元/图层透明
///<summary>
///设置层的透明与否
///</summary>
///<paramname="layerName">层名</param>
///<paramname="opaqueType">不透明类型 ALL 全部不透明BORDER 只有边界不透明(内部透明) NONE 全部透明</param>
///<paramname="borderColor">如果是边界不透明,此处设置边界颜色</param>
publicvoidLayerTransparent(string layerName,OpaqueType opaqueType,System.Drawing.ColorborderColor)
{
MapInfo.Styles.CompositeStyle compositeStyle =GetOpaqueStyle(opaqueType,borderColor);
//创建连接和命令来更新table中的数据
MapInfo.Data.MIConnection connection=newMapInfo.Data.MIConnection();
connection.Open();
MapInfo.Data.MICommandcommand=connection.CreateCommand();
command.CommandText = "update " +layerName + " set obj=obj,MI_Style=@style";
command.Parameters.Add("@style",compositeStyle);
command.Prepare();
command.ExecuteNonQuery();
//关闭连接
command.Cancel();
command.Dispose();
connection.Close();
connection.Dispose();
}
///<summary>
///创建style
///</summary>
///<paramname="opaqueType">不透明类型:ALL全部不透明(白色实心);BORDER边界不透明(填充部分透明);NONE全透明</param>
///<paramname="borderColor">如果opaqueType=BORDER,此处设定边界颜色</param>
///<returns>组合style</returns>
privateMapInfo.Styles.CompositeStyle GetOpaqueStyle(OpaqueTypeopaqueType,System.Drawing.Color borderColor)
{
MapInfo.Styles.SimpleInterior simpleInterior;
if(opaqueType==OpaqueType.ALL)
simpleInterior= newMapInfo.Styles.SimpleInterior(); //缺省构造函数是白色实心
else
simpleInterior= newMapInfo.Styles.SimpleInterior(1); //0是线透明,1是面透明
MapInfo.Styles.LineWidth lineWidth = newMapInfo.Styles.LineWidth(1,MapInfo.Styles.LineWidthUnit.Point);
MapInfo.Styles.SimpleLineStyle simpleLineStyle;
if(opaqueType==OpaqueType.ALL)
simpleLineStyle = newMapInfo.Styles.SimpleLineStyle(lineWidth);
elseif(opaqueType==OpaqueType.BORDER)
simpleLineStyle = newMapInfo.Styles.SimpleLineStyle(lineWidth,2,borderColor); //2表示填充透明,即能够显示轮廓
else
simpleLineStyle = newMapInfo.Styles.SimpleLineStyle(lineWidth,0); //0表示全部透明,即连轮廓都看不到
MapInfo.Styles.AreaStyle areaStyle = newMapInfo.Styles.AreaStyle(simpleLineStyle,simpleInterior);
MapInfo.Styles.CompositeStyle compositeStyle =newMapInfo.Styles.CompositeStyle(areaStyle,null,null,null);
returncompositeStyle;
}
选择全部图元
MapInfo.Engine.Session.Current.Catalog.Search(
table,
MapInfo.Data.SearchInfoFactory.SearchAll(),
MapInfo.Engine.Session.Current.Selections.DefaultSelection,
MapInfo.Data.ResultSetCombineMode.Replace);
设置坐标系
缺省情况下,MapXtreme使用的CoordSys是经纬度投影(LongLat)和WGS84基准面。我想修改投影类型为CoordSysType.TransverseMercator ,基准面为DatumID.Pulkovo1942
MapInfo.Geometry.CoordSysFactorycoordSysFactory=MapInfo.Engine.Session.Current.CoordSysFactory;
mapControl1.Map.SetDisplayCoordSys(coordSysFactory.CreateCoordSys("mapinfo:coordsys8,1001,7,117,0,1,20500000,0"));
coordSysFactory.CreateCoordSys("mapinfo:coordsys8,1001,7,117,0,1,20500000,0") 默认的原点是(B=0,L=117),如果要把原点设在(23,117)应该怎么写这个字符串呢?
coordSysFactory.CreateCoordSys("mapinfo:coordsys8,1001,7,114,23,1,20500000,25000000")
保存新画的层为tab文件
下面的源码是新建一个永久表,然后在表中添加feature,然后保存为硬盘上的tab文件。
privateMapInfo.Data.Table CreateNewMapDataTable(stringtableName)
{
//以下代码是建立永久表
MapInfo.Data.TableInfoNativetableInfoNative=newMapInfo.Data.TableInfoNative(tableName);
tableInfoNative.TablePath=@"D:\DATA\"+tableName+".TAB";
tableInfoNative.Columns.Add(MapInfo.Data.ColumnFactory.CreateIntColumn("ID"));
tableInfoNative.Columns.Add(MapInfo.Data.ColumnFactory.CreateStyleColumn());
MapInfo.Geometry.CoordSys coordSys=mapControl1.Map.GetDisplayCoordSys();
tableInfoNative.Columns.Add(MapInfo.Data.ColumnFactory.CreateFeatureGeometryColumn(coordSys));
MapInfo.Data.Table table=MapInfo.Engine.Session.Current.Catalog.CreateTable(tableInfoNative);
//以下代码是建立临时表
// MapInfo.Data.TableInfo tableInfo=MapInfo.Data.TableInfoFactory.CreateTemp(tableName);
// tableInfo.Columns.Add(MapInfo.Data.ColumnFactory.CreateIntColumn("ID"));
// MapInfo.Data.Table table=MapInfo.Engine.Session.Current.Catalog.CreateTable(tableInfo);
MapInfo.Mapping.FeatureLayerfeatureLayer = newMapInfo.Mapping.FeatureLayer(table);
this.mapControl1.Map.Layers.Add(featureLayer);
returntable;
}
privatevoidAddFeaturesAndSave()
{
MapInfo.Styles.SimpleLineStylesimpleLineStyle = newMapInfo.Styles.SimpleLineStyle(newMapInfo.Styles.LineWidth(1,MapInfo.Styles.LineWidthUnit.Point));
MapInfo.Styles.CompositeStylecompositeStyle = newMapInfo.Styles.CompositeStyle(null,simpleLineStyle,null,null);
MapInfo.Geometry.CoordSys coordSys=mapControl1.Map.GetDisplayCoordSys();
MapInfo.Data.Table table =CreateNewMapDataTable("NewTable");
MapInfo.Data.TableInfo tableInfo =table.TableInfo;
while(……)
{
MapInfo.Data.Feature feature =newMapInfo.Data.Feature(tableInfo.Columns);
feature.Geometry = ……
feature.Style = ……
feature["ID"] = ……
table.InsertFeature(feature);
}
tableInfo.WriteTabFile(); //保存为.tab文件
mapControl1.Refresh();
}
计算缩放比例
///<summary>
///重画控件时计算缩放比例
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>
protectedvoidmapControl1_Paint(object sender,PaintEventArgs e)
{
MapInfo.Geometry.Distance zoomDistance=this.mapControl1.Map.Zoom;
doublezoom=Convert.ToDouble(Convert.ToInt32(zoomDistance.Value*16.09))/10;
this.statusBar1.Text="缩放比例:"+zoom.ToString()+"千米";
MapXtreme开发(一)
1、简单专题图的显示
MapControl1.Map.Clear(); MapGeosetLoadergl=new MapGeosetLoader(@"F:\test.gst"); MapControl1.Map.Load(gl);//打开地图 MapControl1.Map.Load(newMapTableLoader(@"F:\test.tab"));//打开test.tab地图文件 FeatureLayer lyrPnt=MapControl1.Map.Layers["test"] asFeatureLayer; RangedTheme thm = newRangedTheme(lyrPnt,"PH__1999","ph",3,DistributionMethod.EqualCountPerRange);lyrPnt.Modifiers.Insert(0,thm);//定义一个RangedTheme ThemeLegendFrame frame =LegendFrameFactory.CreateThemeLegendFrame("PH__1999","pp",thm);Legend legend = MapControl1.Map.Legends.CreateLegend(new Size(5,5));legend.Frames.Append(frame);//定义一个Legend //MapControl1.Map.Adornments.Append(legend);//如果保留此句,MapControl1中将显示Legend LegendControl1.Map =MapControl1.Map; if (MapControl1.Map.Legends.Count > 0) {LegendControl1.Legend = MapControl1.Map.Legends[0]; }//在LegendControl1控件中显示Legend
2、从MapX到MapXtreme2004[1]-工具选择
在Mapx中为控件选择工具比较迅速,也很直观,如下:Map1.CurrentTool = miZoomInTool miZoomInTool是个枚举量,指定给CurrentTool属性即可,而且象在VB中,直接在等号之后就把备选项就列出来了,非常容易。 在MapXtreme中,这个不起眼的问题却搞得有点麻烦,主要是架构有点变化,设置位置很容易找 MapControl1.MapTools.CurrentTool= 可是,要赋的值却比较麻烦,因为C#中并没有给出智能提示,而且在帮助和对象浏览器中也没有找到什么枚举值。帮助中说要赋String类型,试着MapControl1.MapTools.CurrentTool="ZoomInMapTool"; 但是出错。于是查找帮助,了解MapXtreme中的架构,大致如此:MapTools属于MapControl控件的工具集合,其中已经包含了10个工具,debug中挨个求出如下: 0:ZoomInMapTool 1:ZoomOutMapTool 2:PanMapTool 3:CenterMapTool 4:PointSelectionMapTool 5:RadiusSelectionMapTool 6:RectangleSelectionMapTool 7:PolygonSelectionMapTool 8:DistanceMapTool 9:InfoMapTool 但是要选择工具,却不能用Index,也不能用某项的名字字符串,必须用toolname属性,而且必须这样MapControl1.MapTools.CurrentTool =ZoomInMapTool.Toolname; 因为Toolname是一个静态属性,所以必须用类名来引用,其他别的方式都不行。 看来,以后要用哪个工具,得先查到工具名称,然后才能指定了。
其他相关:
1、Toolname是这几个类的特定属性,在其他的工具类中没有。
2、如果界面中已经放置了同功能的操作控件并关联到MapControl控件,那么将会干扰到程序选择的工具。比如,既放了自带的移动控件,又有一个按钮可以设置移动工具,在点击自定义的按钮,选择移动工具时,那么,界面中的移动控件就会自动处于被按下的状态。这时,再用自定义的选择工具去设置别的功能就不管用了,怎么都是移动功能。所以,最好只要一个就行了。
3、从MapX到MapXtreme2004[2]-图层操作
Mapx中基本的图层操作还是比较简单的,集中在对Layers和Layer的处理上,对别的没有太多要求。 在MapXtreme中,要完成类似功能,发生了一点变化,如下:
1、图层的显示 在MapXtreme中,图层的显示控制发生了奇怪的变化,有一个IsVisible属性,但它是只读的,不能通过它来改变图层的显示。要控制图层的显示与隐藏,可以通过设置Layer.Enable来控制。
2、图层的动态添加 代码如下: Catalog _catalog=MapInfo.Engine.Session.Current.Catalog;MapInfo.Data.Table _tempTable=null; Map _map=MapControl1.Map ; TableInfo ti =TableInfoFactory.CreateTemp("临时"); _tempTable = _catalog.CreateTable(ti);_map.Layers.Insert(0, new FeatureLayer(_tempTable));
可以看出:加图层实际就是加表;Catalog对象统管表的加载以及列举;
查帮助还可以了解:表信息其实还可以包括表的类型和坐标系。类型是指原生表,文本,access ...
上面的ti也可以这样取得,但是,上面的表默认是MeMTab,应该是内存中的吧。 CoordSyscs=_map.GetDisplayCoordSys(); TableInfo ti = TableInfoFactory.CreateTemp("临时",MapInfo.Data.TableType.Native,cs);
4、从MapX到MapXtreme2004[3]-搜索图元
一、根据名称搜索图元
1、Mapxtreme的架构和Mapx有所变化,Mapx中,Layer包含Features,而Mapxtreme中则不是
2、Mapxtreme的例子中的查找,是通过Find对象来实现的,而Find对象的构造,需要指定Table和Colume,Table好办,FeatureLayer.table即可,而Colume通过FeatureLayer.table.tableinfo.colums["列名"]来指定。但是,关键问题,大多数的地图,并未设计过多的字段来供查询,查的其实就是个标题和label而已。
3、要用笨办法,遍历图层的features,通过这个方法 foreach(Feature feature in lyr.table) { }
4、Feature派生自Object,包含一个Geometry属性,这个属性是各种几何图形对象的基类 Geometry classes that derive from FeatureGeometry include: Point,MultiPoint, MultiCurve, MultiPolygon, FeatureGeometryCollection, Rectangle,RoundedRectangle, Ellipse, LegacyArc, and LegacyText.
5、通过如下方式引用feature对象 ((MapInfo.Geometry.LegacyText)feature.Geometry).Caption
二、通过search方法搜索
1、catalog的search方法可以按条件搜索图元(第一个图元) // also uses search for feature Feature fDEU =_catalog.SearchForFeature("europe",MapInfo.Data.SearchInfoFactory.SearchWhere ("Country='DEU'"));
2、先利用SearchInfoFactory构造一个SearchInfo对象,指定其搜索属性: SearchAll: Returns all the rows. SearchNearest: Returns the rows with table geometries that are closest to thegiven search point. SearchWhere: Returns the rows specified by the given where Clause.SearchWithinDistance: Returns the rows where the table geometry is contained within abuffer of the search point, rectangle or geometry. SearchWithinFeature: Returns the rows where the tablegeometry is contained within the search features's geometry.SearchWithinGeometry: Returns the rows where the table geometry is contained within thesearch geometry. SearchWithinRect: Returns the rows where the table geometry intersects the givenrectangle. SearchIntersectsFeature: Returns the rows where the table geometry intersects with thesearch features's geometry. SearchIntersectsGeometry: Returns the rows where the tablegeometry intersects with the search geometry. SearchWithinScreenRadius: Creates a SearchInfo that returnsthe rows where the table geometry intersects a screen circle.SearchWithinScreenRect:Returns the rows where the table geometry intersects the givenscreen rectangle
3、再调用search方法,将结果放到MultiResultSetFeatureCollection IResultSetFeatureCollection
4、或许还要设置视图 MapInfo.Engine.Session.Current.MapFactory[0].SetView(fc.Envelope);
三、通过选择工具来选择一个范围 1、需要控制选择的图层 2、选择的结果,通过MapInfo.Engine.Session.Current.Selections.DefaultSelection得到一个Selection对象 3、Selection对象,是一个IResultSetFeatureCollection的集合,每个对应一个表
4、对每一个IResultSetFeatureCollection,可以通过枚举器来遍历访问 Selection sl=MapInfo.Engine.Session.Current.Selections.DefaultSelection;IResultSetFeatureCollection fc=sl[0]; IFeatureEnumeratorfn=fc.GetFeatureEnumerator(); ListBox1.Items.Clear(); while(fn.MoveNext()) if(fn.Current.Geometry.GetType().ToString()=="MapInfo.Geometry.LegacyText")ListBox1.Items.Add(((MapInfo.Geometry.LegacyText)fn.Current.Geometry).Caption);
5、从MapX到MapXtreme2004[4]-标注
AutoLabel 好日子一去不复返了,原来总觉得Mapx很多地方设计得不是很自然,比如,feature和具体的feature之间的某些属性的关系,有时令人迷惑。但是,用了Mapxtreme,才感觉到Mapx的方便。真不知MapInfo怎么想的!原来的标注非常简单,layer有个autolabel属性,一设就可以了。现在呢: //James.Liu的代码 Table table =Session.Current.Catalog.OpenTable("usa.tab"); Map map =Session.Current.MapFactory.CreateEmptyMap(new Size(300, 300)); LabelLayer layer= new LabelLayer(); map.Layers.Add(layer); LabelSource source = newLabelSource(table); source.DefaultLabelProperties.Caption = "State_Name";layer.Sources.Append(source); //我的 LabelLayer layer = new LabelLayer();MapControl1.Map.Layers.Add(layer); LabelSource source = newLabelSource(MapInfo.Engine.Session.Current.Catalog.GetTable("地名"));source.DefaultLabelProperties.Caption = "f_name"; //标注用到的那个字段名称 layer.Sources.Append(source);看Layer.Sources的架势,好像可以共用一个LabelLayer,试试,的确可以
6、从MapX到MapXtreme2004[5]-自定义工具
从MapX到MapXtreme2004[5]-自定义工具参见月光宝盒的文章http://jerry429.blogchina.com/2149736.html 参见《MapXtreme2004_DevGuide_A4.pdf》 p155 Example
1: Writing a Server SIde Custom Tool 自己的体会: 1、要写一个自定义的事件参数,传递需要的信息
2、最好从一个MapTool派生新的工具类,而不要从现成的工具如点选工具派生,否则会带来很多问题。感谢James.Liu给出的提示http://www.mygis.com.cn/forum/dispbbs.asp?boardID=23&replyID=38340&ID=8090&skin=1
3、创建好的自定义工具,必须先建立实例,加到MapControl的Maptools中,才能被设置为当前工具。还有一点也很重要,Maptools似乎没有Viewstate,每次postback都会还原,所有在pageload中必须每次都加入新工具。
4、自定义工具的类型可以是多种多样,如下: To draw a rectangle: MapInfoWebRectangleStartMapInfoWebRectangleStop To process a click: MapInfoWebPointStartMapInfoWebPointStop To process panning of a map: MapInfoWebPanStart MapInfoWebPanStopTo draw a circle: MapInfoWebCircleStart MapInfoWebCircleStop To draw apolyline: MapInfoWebDistanceStart MapInfoWebDistanceStop To draw a polygon:MapInfoWebPolygonStart MapInfoWebPolygonStop
7、从MapX到MapXtreme2004[6]-对Table、Feature等的理解
一、Table 2004中,Table还是表,可以来自原始的mapinfo表,也可以来自数据库的二维表、文本等。Table的等价概念是feature集合,如下代码: (_tempTable asIFeatureCollection).Clear(); 当然,可以通过枚举器,来逐个访问table的行,如下:Selection sl =MapInfo.Engine.Session.Current.Selections.DefaultSelection;IResultSetFeatureCollection fc=sl[0]; IFeatureEnumeratorfn=fc.GetFeatureEnumerator(); //IFeatureCollection也有GetFeatureEnumeratorListBox1.Items.Clear(); while(fn.MoveNext())if(fn.Current.Geometry.GetType().ToString()=="MapInfo.Geometry.LegacyText")ListBox1.Items.Add(((MapInfo.Geometry.LegacyText)fn.Current.Geometry).Caption);当然,用foreach(Feature feature in tb) 也是毫无问题的,因而,table和结果集是等价的。
二、FeatureFeature等价于表中的行。只与行有关,而与具体的图元的类型无关。换言之,Feature只是指图元对应的表行,而与图元的属性无关。用Feature.Table可以引用到所属的表。用Table.TableInfo可以引用到表的结构信息。 Feature具有的默认列,一般都包括obj,Mi_key,Mi_Style。obj我个人认为就是Feature对应的几何对象。用Feature.Geometry属性可以引用。 Feature.Geometry的类型是FeatureGeometry,它是各种具体图元(点线面文字...)的父类,Feature.Geometry属性所对应的,其实是具体的类。(我向这个属性赋点对象,发现没错)。对Feature的使用,可以通过CataLog的SearchForFeature来查找,如下MapInfo.Engine.Session.Current.Catalog.SearchForFeature("Layer1",MapInfo.Data.SearchInfoFactory.SearchWhere("MI_Key='"+strKey+"'")) 由于ID其实并不唯一,所以,较好的查找对象是MI_Key。同时,Catalog还有其他的查找函数,如SearchNearest等。加入Feature时,往往需要指定这些基本的信息,有多种加入方法。
MapXtreme开发(二)
1、改变地图的坐标系统
使用如下方法改变地图的坐标系统
Mapmap = mapControl1.Map;
MapInfo.Geometry.CoordSys coordSys =Session.Current.CoordSysFactory.CreateLongLat(DatumID.WGS84);//.NAD83);
//DatumID为枚举类型,其中列出了经纬度坐标系统的大量枚举类型,参阅帮助可获取更多信息。
map.SetDisplayCoordSys(coordSys);
2、如何改变一个地图的Zoom单位
mapControl1.Map.Zoom = new MapInfo.Geometry.Distance(mapControl1.Map.Zoom.value,MapInfo.Geometry.DistanceUnit.Kilometer);
也可以分开写成如下格式:
MapInfo.Geometry.Distance d = newMapInfo.Geometry.Distance(1000, DistanceUnit.Kilometer);
mapControl1.Map.Zoom = d;
注意在这里的1000,限制了用户的ZOOM范围只能为1000km。
用以下方法更加合适:
mapControl1.Map.Zoom = newMapInfo.Geometry.Distance(
CoordSys.ConvertDistanceUnits(
DistanceUnit.Kilometer,
mapControl1.Map.Zoom.value,
mapControl1.Map.Zoom.Unit),
DistanceUnit.Kilometer);
3、如何为mapControl中的一个地图表增加主题
如何为mapControl中的一个地图表增加主题?
为SHENGQU这个面样式表来增加主题。
//Listen to some map events
mapControl1.Resize += newEventHandler(mapControl1_Resize);
//在此事件中处理当mapControl改变大小时来重新定位主题表的位置。
//Create a ranged theme on the USAlayer.
Mapmap = mapControl1.Map;
FeatureLayer lyr =map.Layers["SHENGQU"] as MapInfo.Mapping.FeatureLayer;
RangedTheme thm = newMapInfo.Mapping.Thematics.RangedTheme(
lyr,
"Round(MI_Area(Obj, 'sq km', 'Spherical'), 1)",
"Area (square kilometer)",
5,
MapInfo.Mapping.Thematics.DistributionMethod.EqualRangeSize);//.EqualCountPerRange);
lyr.Modifiers.Append(thm);
//Change the default fill colors from Red->Gray to White->Blue
AreaStyle ars;
//Get the style from our first bin
CompositeStyle cs = thm.Bins[0].Style;
// Get the region --Area -- style
ars= cs.AreaStyle;
//Change the fill color
ars.Interior = StockStyles.WhiteFillStyle();
//Update the CompositeStyle with the new region color
cs.AreaStyle = ars;
//Update the bin with the new CompositeStyle settings
thm.Bins[0].Style = cs;
//Change the style settings on the last bin
intnLastBin = thm.Bins.Count - 1;
cs =thm.Bins[nLastBin].Style;
ars= cs.AreaStyle;
ars.Interior = StockStyles.BlueFillStyle();
thm.Bins[nLastBin].Style = cs;
//Tell the theme how to fill in the other bins
thm.SpreadBy = SpreadByPart.Color;
thm.ColorSpreadBy = ColorSpreadMethod.Rgb;
thm.RecomputeStyles();
//Create a legend
legend = map.Legends.CreateLegend(new Size(5,5));
legend.Border = true;
ThemeLegendFrame frame = LegendFrameFactory.CreateThemeLegendFrame("Area","Area", thm);
legend.Frames.Append(frame);
frame.Title = "Area (sq. mi.)";
map.Adornments.Append(legend);
//Set the initial legend location to be the lower right corner of the mapcontrol.
System.Drawing.Point pt = newSystem.Drawing.Point(0, 0);
pt.X= mapControl1.Size.Width - legend.Size.Width;
pt.Y= mapControl1.Size.Height - legend.Size.Height;
legend.Location = pt;
在mapControl1_Resize事件中针对mapControl大小的改变来变化主题表的位置。
private void mapControl1_Resize(object sender,System.EventArgs e)
{
Control control = (Control)sender;
//Move the Legend to the lower right corner...
System.Drawing.Point pt = new System.Drawing.Point(0, 0);
pt.X = control.Size.Width - legend.Size.Width;
pt.Y = control.Size.Height - legend.Size.Height;
legend.Location = pt;
}
5、数据绑定
数据绑定的例子。当数据表中的值改变,Pennsylvania 州的颜色会改变。
private void button1_Click(object sender,System.EventArgs e)
{
Session.Current.Catalog.CloseAll();
Table USATab = USATab =Session.Current.Catalog.OpenTable(@"c:\programfiles\mapinfo\mapxtreme.0\samples\data\usa.tab");
FeatureLayer fl = new FeatureLayer(USATab);
mapControl1.Map.Layers.Add(fl);
System.Data.DataTable dt = newSystem.Data.DataTable("USStuff");
dt.Columns.Add("USState",typeof(System.String));
dt.Columns.Add("SomeIndValue",typeof(System.String));
dt.Rows.Add(new object[]{"NY","Dem"});
dt.Rows.Add(new object[]{"PA","Rep"});
dt.Rows.Add(new object[]{"VT","Dem"});
dt.Rows.Add(new object[]{"OH","Rep"});
TableInfoAdoNet tian = new TableInfoAdoNet("VoteRecord",dt);
Table USVote =Session.Current.Catalog.CreateTable(tian);
Columns cols = new Columns();
cols.Add(USVote.TableInfo.Columns["SomeIndValue"].Clone());
USATab.AddColumns(cols,BindType.DynamicCopy, USVote, "USState", Operator.Equal, "State");
MapInfo.Mapping.Thematics.IndividualValueThemethm = new MapInfo.Mapping.Thematics.IndividualValueTheme(fl,"SomeIndValue", "StateVotingRecord");
fl.Modifiers.Append(thm);
timer1.Start() ;
}
private void timer1_Tick(object sender,System.EventArgs e)
{
FeatureLayer fl = mapControl1.Map.Layers[0]as FeatureLayer;
System.Data.DataTable dt =(Session.Current.Catalog.GetTable("VoteRecord").TableInfo asTableInfoAdoNet).DataTable;
dt.Rows[1][1] =dt.Rows[1][1].ToString()=="Rep"?"Dem":"Rep";
Session.Current.Catalog.GetTable("VoteRecord").Refresh();
fl.Table.Refresh();
fl.Invalidate();
}
6、一段旋转图元几何体的代码
Catalog cata = MapInfo.Engine.Session.Current.Catalog;
Table t = cata.GetTable("World");
Feature f = cata.SearchForFeature(t, MapInfo.Data.SearchInfoFactory.SearchWhere("Country='Japan'"));
DPoint dp = new DPoint(f.Geometry.GeometricCentroid.x,f.Geometry.GeometricCentroid.y);
f.Geometry.GeometryEditor.Rotate(dp, 90);
f.Geometry.EditingComplete();
t.UpdateFeature(f);
mapControl1.Map.SetView(f);
7、在Web应用中使用InfoTip
1.在地图网页的<body>后面加入下面的代码:
<script>
if(!document.layers&&!document.all&&!document.getElementById)
event="test"
function showtip(current,e,text){
if (document.all||document.getElementById){
thetitle=text.split('<br>')
if(thetitle.length>1){
thetitles=''
for(i=0;i<thetitle.length;i++)
thetitles+=thetitle
current.title=thetitles
}
else
current.title=text
}
else if (document.layers){
document.tooltip.document.write('<layer bgColor="white"style="border:1px solidblack;font-size:12px;">'+text+'</layer>')
document.tooltip.document.close()
document.tooltip.left=e.pageX+5
document.tooltip.top=e.pageY+5
document.tooltip.visibility="show"
}
}
function hidetip(){
if (document.layers)
document.tooltip.visibility="hidden"
}
</script>
2。在</body>前加入下面代码:
<scriptlanguage="javascript">
var img =document.getElementById('MapControl1_Image');
img.useMap ="#WOTips";
</script>
3。进入visual studio 2003的IDE,在地图的aspx页上任何地方加入Literal Control。
鼠标右击MapControl选择属性,在MapControl的属性窗口选择事件页,双击PreRender事件,此时PreRender事件注册信息会自动加入到InitializeComponent方法中,同时创建空的private voidMapControl1_PreRender(object sender, System.EventArgs e)处理函数。在PreRender事件处理程序中加入如下代码:
//为不同视野下的地图图像创建热区
StringCollection areaTagCollection = this.getImageMapHotSpots();
string areaHTML = "";
System.Collections.Specialized.StringEnumerator sEnum =areaTagCollection.GetEnumerator();
while (sEnum.MoveNext())
{
areaHTML += ((string) sEnum.Current);
}
Literal1.Text = "<map id ='WOTips' name='WOTips'>" +areaHTML + "</map>";
4。把下面方法加入代码窗口:
private System.Collections.Specialized.StringCollection getImageMapHotSpots()
{
StringCollection areaTags = new StringCollection();
MapInfo.Mapping.Map rMap = MapControl1.Map;
MapInfo.Engine.ISession rMSession= MapInfo.Engine.Session.Current; //获得Session
MapInfo.Data.Catalog catalog = rMSession.Catalog;
MapInfo.Data.Table tabWorld = catalog.GetTable("Worldcap");
MapInfo.Data.MIDataReader dr = tabWorld.ExecuteReader();
while(dr.MoveNext())
{
MapInfo.Geometry.Point sPoint = (MapInfo.Geometry.Point)dr.Current.Geometry;
MapInfo.Geometry.Envelope env = sPoint.Envelope;
MapInfo.Geometry.DRect sRect = env.Bounds;
string tiptext = (string) dr.Current[1];
MapInfo.Geometry.DisplayTransform dt = rMap.DisplayTransform;
System.Drawing.Rectangle rect;
dt.ToDisplay(sRect, out rect);
string coords = (rect.Right-10) + "," + (rect.Top-20) +"," + (rect.Left + 10) +"," + (rect.Bottom + 10);
string tag = "<area shape ='rect' coords ='" + coords +"' οnmοuseοver='showtip(this,event,\""+ tiptext + "\")' onMouseout='hidetip()' />";
areaTags.Add(tag);
}
dr.Dispose();
return areaTags;
}
VB.NET
Private Sub Page_PreRender(ByVal sender As Object, ByVal e AsSystem.EventArgs) Handles MyBase.PreRender
'为不同视野下的地图图像创建热区
Dim areaTagCollection As System.Collections.Specialized.StringCollection= Me.getImageMapHotSpots()
Dim areaHTML As String = ""
Dim sEnum As System.Collections.Specialized.StringEnumerator =areaTagCollection.GetEnumerator()
Do While sEnum.MoveNext
areaHTML += (sEnum.Current.ToString)
Loop
Literal1.Text = "<map id ='WOTips' name='WOTips'>" +areaHTML + "</map>"
End Sub
Private Function getImageMapHotSpots() As System.Collections.Specialized.StringCollection
Dim areaTags As New System.Collections.Specialized.StringCollection
Dim rMap As MapInfo.Mapping.Map = MapControl1.Map
Dim rMSession As MapInfo.Engine.ISession = MapInfo.Engine.Session.Current ' //获得Session
Dim catalog As MapInfo.Data.Catalog = rMSession.Catalog
Dim tabWorld As MapInfo.Data.Table =Catalog.GetTable("Worldcap")
Dim dr As MapInfo.Data.MIDataReader = tabWorld.ExecuteReader()
Do While dr.MoveNext
Dim sPoint As MapInfo.Geometry.Point = dr.Current.Geometry
Dim env As MapInfo.Geometry.Envelope = sPoint.Envelope
Dim sRect As MapInfo.Geometry.DRect = env.Bounds
Dim tiptext As String = dr.Current(1).ToString
Dim dt As MapInfo.Geometry.DisplayTransform = rMap.DisplayTransform
Dim rect As System.Drawing.Rectangle
dt.ToDisplay(sRect, rect)
Dim coords As String = (rect.Right - 10).ToString + "," +(rect.Top - 20).ToString + "," + (rect.Left + 10).ToString +"," + (rect.Bottom + 10).ToString
Dim tag As String = "<area shape = 'rect' coords =' " +coords + " ' οnmοuseοver='showtip(this,event,'+""" + tiptext +""")' onMouseout='hidetip()' />"
areaTags.Add(tag)
Loop
dr.Dispose()
Return areaTags
End Function
8、获取该点的经纬度
/*
A. Creating the MapTool
First ofall, we need to create a new tool. Our tool will derive fromMapInfo.Web.UI.WebControls.MapTool,
just like all the build-in controls. This is an abstract class with 5abstract properties (all string)
and1 abstract method (void) we have to implement.
* PropertyClientCodeSource: Gets or sets the path or URL where the Javascript filecontaining client drawing code
islocated.
* PropertyClientStartMethod: Gets or sets the name of the client side method to set upmouse event handlers
fordrawing.
* PropertyClientStopMethod: Gets or sets the name of the client side method to cancel themouse event handlers.
* PropertyCursorUrl: Gets or sets the path or URL where cursor image file is located.
* PropertyName: Gets or sets the name of the tool.
* MethodExecute: Contains the business logic to do the task.
We simplyhave to implement the properties so their values are stored in a private field.
Theonly properties we have to set ourselves are ClientStartMethod,ClientStopMethod and Name.
We'll setthe Name property in the same way the Name property is implemented by the othertools.
We'lluse a static field 'Toolname', set it to 'GetPointTool' (the name of our tool)and assing it to
theprivate _name field in the constructor of our tool.
According tothe MapXtreme 2004 Developers guide, we'll need to use the MapInfoWebPointStartand
MapInfoWebPointStop javascript methods tohandle a mapclick, so we'll set the private _clientStartMethod
andclientStopMethod fields to these values in the constructor
Sobasically, our class would look like this:
*/
using System;
using MapInfo.Web.UI.WebControls;
namespace WebMapXY
{
/*
At this point, we could add ourtool logic in the Execute method, but this would mean our tool would alwaysbehave the same. Instead, we'll add an event that we'll raise from the ExecuteMethod. To stay consistent, we'll create an EventArgs class called PointFoundEventArgsin which we'll put our point data. The class will inherit from System.EventArgsand will look like this:
*/
public class PointFoundEventArgs: EventArgs
{
private MapInfo.Mapping.Map _map;
private MapInfo.Geometry.DPoint _point;
public PointFoundEventArgs(MapInfo.Mapping.Map map,MapInfo.Geometry.DPoint point)
{
this ._map = map;
this._point = point;
}
public MapInfo.Mapping.Map Map
{
get { return _map; }
set { _map = value; }
}
public MapInfo.Geometry.DPoint Point
{
get { return _point; }
set { _point = value; }
}
}
///<summary>
///GetPointTool 的摘要说明。
///</summary>
public class GetPointTool :MapInfo.Web.UI.WebControls.MapTool
{
private string _clientStartMethod;
private string _clientStopMethod;
private string _clientSourceCode;
private string _cursorUrl;
private string _name;
public static readonly string Toolname = "GetPointTool";
public delegate void PointFoundEventHandler(object sender,PointFoundEventArgs e);
public event PointFoundEventHandler PointFound;
public override string Name
{
get
{
return _name;
}
set { _name = value; }
}
public override string ClientCodeSource
{
get { return _clientSourceCode; }
set { _clientStartMethod = value; }
}
public override string ClientStartMethod
{
get { return _clientStartMethod; }
set { _clientStartMethod = value; }
}
public override string ClientStopMethod
{
get { return _clientStopMethod; }
set { _clientStopMethod = value; }
}
public override string CursorUrl
{
get { return _cursorUrl; }
set { _cursorUrl = value; }
}
public GetPointTool()
{
Name = Toolname;
_clientSourceCode= null ;
_clientStartMethod = "MapInfoWebPointStart";
_clientStopMethod = "MapInfoWebPointStop";
}
public override void Execute(string dataString,System.Collections.ArrayList arrayList, MapInfo.Mapping.Map map)
{
MapInfo.Geometry.DPoint Point;
//Extractthe point from the datastring
System.Drawing.Point [] points = base.ExtractPoints(dataString);
//convert it to usable coordinates
map.DisplayTransform.FromDisplay(points[0], out Point);
//create a new PointsFoundEventArgs and set the Point property (throughthe constructor)
PointFoundEventArgs e = new PointFoundEventArgs(map, Point);
//Fire our event
PointFound(this, e);
}
}
/* Creating the ToolControl
To make thetool usable like the other MapInfo tools, we'll need to create a newToolControl.
Tocreate a new ToolControl, we'll derrive from theMapInfo.Web.UI.WebControls.ToolControl class.
We'll create an event that will point at thePointFound event of our Tool.
Inthe constructor of the class, we will set default values for properties like'ActiveImageUrl' and 'crsorImageUrl'.
We'lloverride the OnLoad event to create a new instance of our Tool,
setthe MapTool property of the ToolControl to it and add it to the MapToolscollection of the MapControl.
We'll also point the PointFound event of theToolControl to the PointFound event of the ToolControl.
*/
public class GetPointToolControl :MapInfo.Web.UI.WebControls.ToolControl
{
public event GetPointTool.PointFoundEventHandler PointFound;
public GetPointToolControl()
{
//Tooltip to display on the client.
this.TooltipText = "点击地图,获取该点的经纬度";
//set the location of the cur file that will be the cursor
this.crsorImageUrl = MapInfoMapTool.GetResourcePath() +"/MapInfoWebPointSelection.cur";
//set the location of the gif files that will be the tool buttons
this.ActiveImageUrl = MapInfoMapTool.GetResourcePath() +"/PointSelectionToolControlActive.gif";
this.InactiveImageUrl = MapInfoMapTool.GetResourcePath() +"/PointSelectionToolControlInActive.gif";
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if(this.mapControl != null)
{
GetPointTool tool = new GetPointTool();
this.MapTool = tool;
this.mapControl.MapTools.Add(tool);
tool.PointFound+=PointFound;
}
}
}
}