MapXtreme开发(二)

1、改变地图的坐标系统
使用如下方法改变地图的坐标系统
Map map = 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 = new MapInfo.Geometry.Distance(1000, DistanceUnit.Kilometer);
mapControl1.Map.Zoom = d;
注意在这里的1000,限制了用户的ZOOM范围只能为1000km。

用以下方法更加合适:
mapControl1.Map.Zoom = new MapInfo.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 += new EventHandler(mapControl1_Resize);
//在此事件中处理当mapControl改变大小时来重新定位主题表的位置。

// Create a ranged theme on the USA layer.
Map map = mapControl1.Map;
FeatureLayer lyr = map.Layers["SHENGQU"] as MapInfo.Mapping.FeatureLayer;

RangedTheme thm = new MapInfo.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
int nLastBin = 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 map control.
System.Drawing.Point pt = new System.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:/program files/mapinfo/mapxtreme.0/samples/data/usa.tab");
FeatureLayer fl = new FeatureLayer(USATab);
mapControl1.Map.Layers.Add(fl);

System.Data.DataTable dt = new System.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.IndividualValueTheme thm = 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 as TableInfoAdoNet).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.在地图网页的后面加入下面的代码:

<script>

            if (!document.layers&&!document.all&&!document.getElementById)
                        event="test"
            function showtip(current,e,text){

                        if (document.all||document.getElementById){
                        thetitle=text.split('
')
                        if (thetitle.length>1){
                        thetitles=''
                        for (i=0;i
                        thetitles+=thetitle
                        current.title=thetitles
                        }
                        else
                        current.title=text
                        }

                        else if (document.layers){
                        document.tooltip.document.write(' '+text+' ')
                        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。在前加入下面代码:

<script language="javascript">
                  var img = document.getElementById('MapControl1_Image');
                  img.useMap = "#WOTips";
</script>

3。进入visual studio 2003的IDE,在地图的aspx页上任何地方加入Literal Control。
鼠标右击Map Control选择属性,在Map Control的属性窗口选择事件页,双击PreRender 事件,此时PreRender事件注册信息会自动加入到InitializeComponent方法中,同时创建空的private void MapControl1_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 = "" + areaHTML + "";

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 = "";
    areaTags.Add(tag);
   }
   dr.Dispose();
   return areaTags;
  }
VB.NET

   Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.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 = "" + areaHTML + ""

    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 = ""
            areaTags.Add(tag)
        Loop
        dr.Dispose()
        Return areaTags

    End Function
8、获取该点的经纬度

/*

A. Creating the MapTool
First of all, we need to create a new tool. Our tool will derive from MapInfo.Web.UI.WebControls.MapTool,
  just like all the build-in controls. This is an abstract class with 5 abstract properties (all string)
  and 1 abstract method (void) we have to implement.
* Property ClientCodeSource: Gets or sets the path or URL where the Javascript file containing client drawing code
  is located.
* Property ClientStartMethod: Gets or sets the name of the client side method to set up mouse event handlers
for drawing.
* Property ClientStopMethod: Gets or sets the name of the client side method to cancel the mouse event handlers.
* Property CursorUrl: Gets or sets the path or URL where cursor image file is located.
* Property Name: Gets or sets the name of the tool. 
* Method Execute: Contains the business logic to do the task.
We simply have to implement the properties so their values are stored in a private field.
The only properties we have to set ourselves are ClientStartMethod, ClientStopMethod and Name.
We'll set the Name property in the same way the Name property is implemented by the other tools.
  We'll use a static field 'Toolname', set it to 'GetPointTool' (the name of our tool) and assing it to
  the private _name field in the constructor of our tool.
According to the MapXtreme 2004 Developers guide, we'll need to use the MapInfoWebPointStart and
MapInfoWebPointStop javascript methods to handle a mapclick, so we'll set the private _clientStartMethod
and clientStopMethod fields to these values in the constructor
So basically, our class would look like this:
*/

using System;
using MapInfo.Web.UI.WebControls;
namespace WebMapXY
{
/*
  At this point, we could add our tool logic in the Execute method, but this would mean our tool would always behave the same. Instead, we'll add an event that we'll raise from the Execute Method. To stay consistent, we'll create an EventArgs class called PointFoundEventArgs in which we'll put our point data. The class will inherit from System.EventArgs and 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; }
  }
}
///


/// GetPointTool 的摘要说明。
///

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;
   //Extract the 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 (through the constructor)
   PointFoundEventArgs e = new PointFoundEventArgs(map, Point);
   //Fire our event
   PointFound(this, e);
  }

}

/* Creating the ToolControl
To make the tool usable like the other MapInfo tools, we'll need to create a new ToolControl.
To create a new ToolControl, we'll derrive from the MapInfo.Web.UI.WebControls.ToolControl class.
We'll create an event that will point at the PointFound event of our Tool.
In the constructor of the class, we will set default values for properties like 'ActiveImageUrl' and 'crsorImageUrl'.
We'll override the OnLoad event to create a new instance of our Tool,
set the MapTool property of the ToolControl to it and add it to the MapTools collection of the MapControl.
We'll also point the PointFound event of the ToolControl 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;
   }
  }
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值