MapGuide 添加临时点图层

下面代码是实现添加临时图层,并在临时图层上加点的功能,永久图层类似。

//AddLayer aspx.cs

protected void Page_Load(object sender, EventArgs e)
{


NameValueCollection parameters
= Request.HttpMethod == "POST" ? Request.Form : Request.QueryString;
string sessionId = parameters["SESSION"].ToString();//session
string mapName=parameters["MAPNAME"].ToString();
MgSiteConnection siteConnection
= new MgSiteConnection();//site
MgUserInformation userInfo = new MgUserInformation(sessionId);
siteConnection.Open(userInfo);

MgResourceService resourceService
= (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
MgFeatureService featureService
= (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

//打开地图
MgMap map = new MgMap();
Page.Response.Write(mapName
+"<br>");
map.Open(resourceService, mapName);
string layerName = "Points";
string layerLegendLabel = "New Points";
String groupName
= "Analysis";
String groupLegendLabel
= "New Analysis";


//创建临时要素源
string featureSourceName = "Session:" + sessionId + "//TemporaryPoints.FeatureSource";
Page.Response.Write(
"临时要素源:"+featureSourceName+"<br>");
string layerDefinitionTemp = @"Library://Samples/Sheboygan/Data/Rail.FeatureSource";
MgResourceIdentifier resourceIdentifier
= new MgResourceIdentifier(featureSourceName);

//////////////////////////////////////////////////////////////////////////
// MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(layerDefinitionTemp);
//////////////////////////////////////////////////////////////////////////

bool featureSourceExists = DoesResourceExist(resourceIdentifier, resourceService);
if (!featureSourceExists)
{
//创建一个临时要素源
//创建一个要素类定义以创建新的要素
MgClassDefinition classDefinition = new MgClassDefinition();
classDefinition.SetName(
"Points");
classDefinition.SetDescription(
"Points to display");
string geometryProrpertyName = "SHPGEOM";
classDefinition.SetDefaultGeometryPropertyName(geometryProrpertyName);

//创建一个identify属性
MgDataPropertyDefinition identifyPropertify = new MgDataPropertyDefinition("KEY");
identifyPropertify.SetDataType(MgPropertyType.Int32);
identifyPropertify.SetAutoGeneration(
true);
//identifyPropertify.SetReadOnly(true);
//////////////////////////////////////////////////////////////////////////
identifyPropertify.SetReadOnly(false);
//////////////////////////////////////////////////////////////////////////

//添加一个identify属性到类定义中
classDefinition.GetIdentityProperties().Add(identifyPropertify);
classDefinition.GetProperties().Add(identifyPropertify);

//创建一个name属性
MgDataPropertyDefinition nameProperty = new MgDataPropertyDefinition("NAME");
nameProperty.SetDataType(MgPropertyType.String);
//添加name属性到类定义中
classDefinition.GetProperties().Add(nameProperty);

//创建一个geometry属性
MgGeometricPropertyDefinition geometryProrpertyDef = new MgGeometricPropertyDefinition(geometryProrpertyName);
geometryProrpertyDef.SetGeometryTypes(MgFeatureGeometricType.Surface);
//添加geometry属性到类定义中
classDefinition.GetProperties().Add(geometryProrpertyDef);

//创建一个要素模式
MgFeatureSchema featureSchema = new MgFeatureSchema("SHP_Schema", "Point schema");
//添加要素模式到类定义中
featureSchema.GetClasses().Add(classDefinition);

//创建要素源
String wkt=map.GetMapSRS();
MgCreateSdfParams sdfParam
= new MgCreateSdfParams("LL84", wkt, featureSchema);
featureService.CreateFeatureSource(resourceIdentifier, sdfParam);
Page.Response.Write(
"创建临时要素源完毕!<br>");
}
double x0, y0;
x0
= -87.729312;
y0
= 43.743674;

//添加点到要素源
MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();

//////////////////////////////////////////////////////////////////////////
Response.Write("添加点前:" + batchPropertyCollection.GetCount().ToString() + "<br>");
//////////////////////////////////////////////////////////////////////////

MgPropertyCollection PropertyCollection
= MakePoint("Point A", x0, y0);
batchPropertyCollection.Add(PropertyCollection);

//////////////////////////////////////////////////////////////////////////
Response.Write("添加点后:"+batchPropertyCollection.GetCount().ToString()+"<br>");
//////////////////////////////////////////////////////////////////////////

//添加batch属性集到要素源
MgInsertFeatures cmd = new MgInsertFeatures(layerName, batchPropertyCollection);
MgFeatureCommandCollection featureCommandCollection
= new MgFeatureCommandCollection();
featureCommandCollection.Add(cmd);

//执行‘add'命令
featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);

String realPath
= Request.ServerVariables["APPL_PHYSICAL_PATH"];
String rootPath
= realPath;

bool layerExist = DoesLayerExist(layerName, map);
if (!layerExist)
{
//创建一个使用要素源的新的图层
//创建点的样式信息

LayerDefinitionFactory factory
= new LayerDefinitionFactory();
factory.RootDirectoryPath
= realPath;

//string resourceId = "Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
string resourceId = @"Library://Samples/Sheboygan/Symbols/BasicSymbols.SymbolLibrary";
string symbolName = "PushPin";
string width = "24";//points;
string height = "24";//points;
string color = "FF0000FF";
string markSymbol=factory.CreateMarkSymbol(resourceId, symbolName, width, height, color);

//创建一个TEXT规则
string text = "ID";
string frontHeight = "22";
string foregroundColor = "FF0000FF";
string textSymbol=factory.CreateTextSymbol(text,frontHeight,foregroundColor);

//创建点规则
string legendLabel = "trees";
string filter = "";
string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol);

//创建一个点样式
string pointTypeStyle=factory.CreatePointTypeStyle(pointRule);

//创建一个比例尺范围
string minScale="10";
string maxScale="10000000";
string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

//创建图层定义
string featureClass = "Library://Samples/Sheboygan/Data/Points.FeatureSource";
string featureName = "SHP_Schema:Points";
string geometry = "SHPGEOM";
string layerDerfinition = factory.CreateLayerDefinition(featureSourceName , featureName, geometry, pointScaleRange);

//添加图层到当前地图中
MgLayer newLayer;
newLayer
=AddLayerDefinitionToMap(layerDerfinition, layerName, layerLegendLabel, sessionId, resourceService, map);

//添加图层到一个图层集合中
//////////////////////////////////////////////////////////////////////////
AddlayerToGroup(newLayer, groupName, groupLegendLabel, map);
//////////////////////////////////////////////////////////////////////////
Page.Response.Write("创建新图层完毕!<br>");

}

//打开地图的可见性
//如果该图层没有存在当前地图中,当添加它时会默认可见
//但当用户运行这段脚本时,可能设置图层是不可见的
MgLayerCollection layerCollection = map.GetLayers();
if (layerCollection.Contains(layerName))
{
MgLayer lineLayer
= (MgLayer)layerCollection.GetItem(layerName);
lineLayer.SetVisible(
true);
lineLayer.ForceRefresh();
Page.Response.Write(
"图层可见!!<br>");
}

//////////////////////////////////////////////////////////////////////////
MgLayerGroupCollection layerGroupCollection = map.GetLayerGroups();
if (layerGroupCollection.Contains(groupName))
{
MgLayerGroup layergroup
= layerGroupCollection.GetItem(groupName);
layergroup.SetVisible(
true);
Page.Response.Write(
"图层组可见!!<br>");
}
//////////////////////////////////////////////////////////////////////////

//保存地图到会话库中
string sessionName = "Session:" + sessionId + "//" + mapName + ".Map";
Page.Response.Write(sessionName
+"<br>");
MgResourceIdentifier sessionResourceID
= new MgResourceIdentifier(sessionName);
sessionResourceID.Validate();
map.Save(resourceService, sessionResourceID);

try
{
MgByteSink byteSink
= new MgByteSink(resourceService.GetResourceContent(sessionResourceID));
string filePath = "E:\\Temp\\LayerDefinition.xml";
byteSink.ToFile(filePath);
}
catch (MgException ee)
{
Page.Response.Write(ee.GetDetails());
}

MgLayerCollection layers
= map.GetLayers();
foreach (MgLayerBase layer in layers)
{
Response.Write(layer.Name);
Response.Write(
"<br/>");
}
MgLayerGroupCollection layerGroup
=map.GetLayerGroups();
Response.Write(
"LayerGroup Numbers is:"+layerGroup.GetCount());




}
1 public MgPropertyCollection MakeLine(string name,double x0,double y0,double x1,double y1)
2 {
3 MgPropertyCollection propertyCollection=new MgPropertyCollection();
4 MgStringProperty nameProperty=new MgStringProperty("NAME",name);
5 propertyCollection.Add(nameProperty);
6
7 MgWktReaderWriter wktReaderWriter=new MgWktReaderWriter();
8 MgAgfReaderWriter agfReaderWriter=new MgAgfReaderWriter();
9
10 MgGeometry geometry = wktReaderWriter.Read("POINT XY (" + x0 + " " + y0 + ")");
11 MgByteReader byteReader=agfReaderWriter.Write(geometry);
12 MgGeometryProperty geometryProperty=new MgGeometryProperty("SHPGEOM",byteReader);
13 propertyCollection.Add(geometryProperty);
14
15 return propertyCollection;
16 }
17
18 public MgPropertyCollection MakePoint(string name, double x, double y)
19 {
20 MgPropertyCollection propertyCollection = new MgPropertyCollection();
21 MgStringProperty nameProperty = new MgStringProperty("NAME", name);
22 propertyCollection.Add(nameProperty);
23
24 MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
25 MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
26
27 MgGeometry geometry = wktReaderWriter.Read("POINT XY (" + x.ToString() + " " + y.ToString() + ")");
28 MgByteReader geometryByteReader = agfReaderWriter.Write(geometry);
29 MgGeometryProperty geometryProperty = new MgGeometryProperty("SHPGEOM", geometryByteReader);
30 propertyCollection.Add(geometryProperty);
31
32
33 return propertyCollection;
34 }
35
36 public bool DoesResourceExist(MgResourceIdentifier resourceID,MgResourceService resourceService )//存在返回true,不存在返回false
37   {
38 try
39 {
40 MgByteReader byteReader;
41 byteReader=resourceService.GetResourceContent(resourceID);
42 }
43 catch (MgResourceNotFoundException e)
44 {
45 return false;
46 }
47
48 return true;
49 }
50
51 public bool DoesLayerExist(string layName, MgMap map)
52 {
53 Page.Response.Write("DoesLayerExist DONE!<br>");
54 MgLayerCollection layerCollection = map.GetLayers();
55 return (layerCollection.Contains(layName) ? true : false);
56
57 }
58
59 public MgLayer AddLayerDefinitionToMap(string layerDerfinition,string layerName,
60 string layerLegendLabel,string sessionId,MgResourceService resourceService,MgMap map)
61 {
62 // Adds the layer definition (XML) to the map.
63 // Returns the layer.
64  
65 MgLayer newLayer;
66 XmlDocument doc=new XmlDocument();
67 doc.LoadXml(layerDerfinition);
68
69 // 将新的图层定义保存到会话资源库(session repository)
70   int length=layerDerfinition.Length;
71 //////////////////////////////////////////////////////////////////////////
72   Page.Response.Write("layerDerfintion is: "+layerDerfinition + "<br>");
73 Page.Response.Write("length is: "+length.ToString() + "<br>");
74 //////////////////////////////////////////////////////////////////////////
75
76 MgByteSource bytesource = new MgByteSource( Encoding.UTF8.GetBytes(layerDerfinition), length);
77
78 bytesource.SetMimeType(MgMimeType.Xml);
79 MgResourceIdentifier resourceID=new MgResourceIdentifier("Session:"+sessionId+"//"+layerName+".LayerDefinition");
80 resourceService.SetResource(resourceID,bytesource.GetReader(),null);
81 newLayer=AddlayerResourceToMap(resourceID,resourceService,layerName,layerLegendLabel,map);
82 Page.Response.Write("Adds a NewLayer! LayerName is:<h1>"+newLayer.ToString()+"</h1><br>");
83 return newLayer;
84
85
86 }
87
88 //将图层添加到地图中,并返回新建的图层
89 public MgLayer AddlayerResourceToMap(MgResourceIdentifier resourceID,MgResourceService resourceService,
90 string layerName,string layerLegendLabel,MgMap map)
91 {
92 MgLayer newLayer = new MgLayer(resourceID,resourceService);
93 newLayer.SetName(layerName);
94 newLayer.SetVisible(true);
95 newLayer.SetLegendLabel(layerLegendLabel);
96 newLayer.SetDisplayInLegend(true);
97 MgLayerCollection layerCollection= map.GetLayers();
98
99 if (!layerCollection.Contains(layerName))//Returns true if the collection contains the specified item, or false otherwise.
100 {
101 layerCollection.Insert(0, newLayer);
102 Page.Response.Write("图层已加载到地图中!<br>");
103 }
104
105 //////////////////////////////////////////////////////////////////////////
106 MgLayerCollection layers = map.GetLayers();
107 foreach (MgLayerBase layer in layers)
108 {
109 Response.Write(layer.Name);
110 Response.Write("<br/>");
111 }
112 //////////////////////////////////////////////////////////////////////////
113 return newLayer;
114
115 }
116
117 public void AddlayerToGroup(MgLayer layer, String layerGroupName,
118 String layerGroupLegendLabel, MgMap map )
119 {
120 MgLayerGroupCollection layerGroupCollection = map.GetLayerGroups();
121 MgLayerGroup layerGroup;
122 if (layerGroupCollection.Contains((layerGroupName)))
123 {
124 layerGroup = layerGroupCollection.GetItem(layerGroupName);
125 }
126 else
127 {
128 //图层不存在则创建
129 layerGroup = new MgLayerGroup(layerGroupName);
130 layerGroup.SetVisible(true);
131 layerGroup.SetDisplayInLegend(true);
132 layerGroup.SetLegendLabel(layerGroupLegendLabel);
133 layerGroupCollection.Add(layerGroup);
134 }
135 //将图层加入到图层组中
136 layer.SetGroup(layerGroup);
137 Page.Response.Write("图层已加入到图层组中!<br>");
138 }
139
140
141 public MgLayer CreateLayerResource(MgResourceIdentifier resourceID,MgResourceService resourceService,
142 String layerName,String legendLabel,MgMap map)
143 {
144 MgLayer newLayer = new MgLayer(resourceID, resourceService);
145 //添加图层
146 newLayer.SetName(layerName);
147 newLayer.SetVisible(true);
148 newLayer.SetLegendLabel(legendLabel);
149 newLayer.SetDisplayInLegend(true);
150 MgLayerCollection layerCollection=map.GetLayers();
151 if (!layerCollection.Contains(layerName))
152 {
153 layerCollection.Insert(0, newLayer);
154 }
155 layerCollection.Insert(0, newLayer);
156
157
158 return newLayer;
159 }

//LayerDefinitionFactory 类

1 public class LayerDefinitionFactory
2 {
3
4 String rootDirectoryPath = "";
5
6 public String RootDirectoryPath
7 {
8 get { return rootDirectoryPath; }
9 set { rootDirectoryPath = value; }
10 }
11
12
13 private String LoadTemplateFile(String filePath)
14 {
15 StreamReader sr = File.OpenText(rootDirectoryPath +"..\\"+ filePath);
16 return sr.ReadToEnd();
17 }
18
19
20 private String Substitute(String templ, String[] vals)
21 {
22 StringBuilder res = new StringBuilder();
23 int index = 0, val = 0;
24 bool found;
25 do
26 {
27 found = false;
28 int i = templ.IndexOf('%', index);
29 if (i != -1)
30 {
31 found = true;
32 res.Append(templ.Substring(index, i - index));
33 if (i < templ.Length - 1)
34 {
35 if (templ[i + 1] == '%')
36 res.Append('%');
37 else if (templ[i + 1] == 's')
38 res.Append(vals[val++]);
39 else
40 res.Append('@'); //add a character illegal in jscript so we know the template was incorrect
41 index = i + 2;
42 }
43 }
44 } while (found);
45 res.Append(templ.Substring(index));
46 return res.ToString();
47 }
48
49
50
51 /// <summary>
52 /// Creates Area Rule
53 ///
54 /// </summary>
55 /// <param name="legendLabel">string for the legend label</param>
56 /// <param name="filterText">filter string</param>
57 /// <param name="foreGroundColor">color code for the foreground color</param>
58 /// <returns></returns>
59 public String CreateAreaRule(string legendLabel, string filterText, string foreGroundColor)
60 {
61 String areaRule = LoadTemplateFile("/viewerfiles/arearule.templ");
62
63 String[] vals = {
64 legendLabel,
65 filterText,
66 foreGroundColor
67 };
68 areaRule = Substitute(areaRule, vals);
69 return areaRule;
70 }
71
72 /// <summary>
73 /// Creates the area type style.
74 /// </summary>
75 /// <param name="areaRules">The area rules.Call CreateAreaRule to create area rules</param>
76 /// <returns></returns>
77 public string CreateAreaTypeStyle(string areaRules)
78 {
79 string style = LoadTemplateFile("/viewerfiles/areatypestyle.templ");
80 string[] strCollection = { areaRules };
81 style = Substitute(style, strCollection);
82 return style;
83
84 }
85
86
87
88 /// <summary>
89 /// Creates the line rule.
90 /// </summary>
91 /// <param name="legendLabel">The legend label string.</param>
92 /// <param name="filter">The filter string.</param>
93 /// <param name="color">The color code for the line</param>
94 /// <returns></returns>
95 public string CreateLineRule(string legendLabel, string filter, string color)
96 {
97 string lineRule = LoadTemplateFile("/viewerfiles/linerule.templ");
98 string[] strColletion = { legendLabel, filter, color };
99 lineRule = Substitute(lineRule, strColletion);
100 return lineRule;
101 }
102
103
104 /// <summary>
105 /// Creates the line type style.
106 /// </summary>
107 /// <param name="lineRules">The line rules.Call CreateLineRule to create line rules</param>
108 /// <returns></returns>
109 public string CreateLineTypeStyle(string lineRules)
110 {
111 string lineStyle = LoadTemplateFile("/viewerfiles/linetypestyle.templ");
112 string[] strCollection = { lineRules };
113 lineStyle = Substitute(lineStyle, strCollection);
114 return lineStyle;
115 }
116
117
118 /// <summary>
119 /// Creates the mark symbol.
120 /// </summary>
121 /// <param name="resourceId">The resource identifier for the resource to be used</param>
122 /// <param name="symbolName">Name of the symbol.</param>
123 /// <param name="width">The width.</param>
124 /// <param name="height">The height.</param>
125 /// <param name="color">The color.</param>
126 /// <returns></returns>
127 public string CreateMarkSymbol(string resourceId, string symbolName, string width, string height, string color)
128 {
129 string markSymbol = LoadTemplateFile("/viewerfiles/marksymbol.templ");
130 string[] strCollection = { width, height, resourceId, symbolName, color };
131 markSymbol = Substitute(markSymbol, strCollection);
132 return markSymbol;
133 }
134
135 public string CreateMarkSymbol(string resourceId, string symbolName, int width, int height, Color color)
136 {
137 return CreateMarkSymbol(resourceId, symbolName, width.ToString(), height.ToString(), color.ToString());
138
139 }
140
141 /// <summary>
142 /// Creates the text symbol.
143 /// </summary>
144 /// <param name="text">The text string.</param>
145 /// <param name="fontHeight">Height of the font.In Point unit</param>
146 /// <param name="foregroundColor">Color of the foreground.</param>
147 /// <returns></returns>
148 public string CreateTextSymbol(string text, string fontHeight, string foregroundColor)
149 {
150 string textSymbol = LoadTemplateFile("/viewerfiles/textsymbol.templ");
151 string[] strCollection = { fontHeight, fontHeight, text, foregroundColor };
152 textSymbol = Substitute(textSymbol, strCollection);
153 return textSymbol;
154 }
155
156 /// <summary>
157 /// Creates the point rule.
158 /// </summary>
159 /// <param name="legendLabel">The string for the legend label.</param>
160 /// <param name="filter">The string for the filter.</param>
161 /// <param name="label">The label.Use CreateTextSymbol to create it</param>
162 /// <param name="pointSym">The point symbolization. Use CreateMarkSymbol to create it</param>
163 /// <returns></returns>
164 public string CreatePointRule(string legendLabel, string filter, string label, string pointSym)
165 {
166 string pointRule = LoadTemplateFile("/viewerfiles/pointrule.templ");
167 string[] strCollection = { legendLabel, filter, label, pointSym };
168 pointRule = Substitute(pointRule, strCollection);
169 return pointRule;
170 }
171
172 /// <summary>
173 /// Creates the point type style.
174 /// </summary>
175 /// <param name="pointRule">The point rule.Call CreatePointRule to define rules</param>
176 /// <returns></returns>
177 public string CreatePointTypeStyle(string pointRule)
178 {
179 string pointTypeStyle = LoadTemplateFile("/viewerfiles/pointtypestyle.templ");
180 string[] strCollection = { pointRule };
181 pointTypeStyle = Substitute(pointTypeStyle, strCollection);
182 return pointTypeStyle;
183 }
184
185
186 /// <summary>
187 /// Creates the scale range.
188 /// </summary>
189 /// <param name="minScale">The min scale.</param>
190 /// <param name="maxScale">The max scale.</param>
191 /// <param name="typeStyle">The type style.use one CreateAreaTypeStyle, CreateLineTypeStyle, or CreatePointTypeStyle</param>
192 /// <returns></returns>
193 public string CreateScaleRange(string minScale, string maxScale, string typeStyle)
194 {
195 string scaleRange = LoadTemplateFile("/viewerfiles/scalerange.templ");
196 string[] strCollection = { minScale, maxScale, typeStyle };
197 scaleRange = Substitute(scaleRange, strCollection);
198 return scaleRange;
199 }
200
201
202 /// <summary>
203 /// Creates the layer definition.
204 /// </summary>
205 /// <param name="resourceId">resource identifier for the new layer</param>
206 /// <param name="featureClass">the name of the feature class.
207 /// Within a single feature source there may be one or more feature classes. A
208 /// feature class describes a subset of the features in the feature source. In many
209 /// cases, there is one feature class for each feature source. For example, there may
210 /// be a Roads feature class in the RoadCenterLines feature source.A feature class contains one or more features.
211 /// </param>
212 /// <param name="geometry">The geometry.</param>
213 /// <param name="featureClassRange">The feature class range. use CreateScaleRange to define it.</param>
214 /// <returns></returns>
215 public string CreateLayerDefinition(string resourceId, string featureClass, string geometry, string featureClassRange)
216 {
217 string layerDef = LoadTemplateFile("/viewerfiles/layerdefinition.templ");
218 string[] strCollection = { resourceId, featureClass, geometry, featureClassRange };
219 layerDef = Substitute(layerDef, strCollection);
220
221 return layerDef;
222 }
223
224 public LayerDefinitionFactory()
225 {
226 //
227 // TODO: Add constructor logic here
228 //
229 }
230
231 }

posted @ 2011-05-09 19:30  xinjun  阅读(1004)  评论(3编辑  收藏  举报