// Searches the map for a layer with the specified name. public static MgLayer GetLayerByName(MgMap map, String layerName) { MgLayer layer = null; for (int i = 0; i < map.GetLayers().GetCount(); i++) { MgLayer nextLayer = (MgLayer)map.GetLayers().GetItem(i); if (nextLayer.GetName().Equals(layerName)) { layer = nextLayer; break; } } return layer; }
public bool ClearSpatialFilter() { bool result = true; MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource"); MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgMap map = new MgMap(); map.Open(resourceService, Request["MAPNAME"]); MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection(); MgLayer layer = null; MgLayerCollection layers = map.GetLayers(); if (layers.Contains("_QuerySpatialFilter")) { layer = (MgLayer)layers.GetItem("_QuerySpatialFilter"); updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0")); featureService.UpdateFeatures(sdfResId, updateCommands, false); layers.Remove(layer); map.Save(resourceService); } return result; }
// GET: Search/Results public ActionResult Results(SearchInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers[lidx]; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on //query execution when this filter is parsed to a FDO filter. switch (input.By) { case "OWNER": query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "ADDRESS": query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "BBOX": double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); if (parts.Length != 4) { throw new Exception("Invalid BBOX parameter"); } MgWktReaderWriter wktRw = new MgWktReaderWriter(); MgGeometry filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3])); query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects); break; default: throw new Exception("Unknown query type: " + input.By); } SearchResultViewModel vm = new SearchResultViewModel(); vm.Session = input.Session; vm.MapName = input.MapName; vm.LoadResults(layer, query); return(View(vm)); }
// GET: Search/Results public ActionResult Results(SearchInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers.GetItem(lidx); MgFeatureQueryOptions query = new MgFeatureQueryOptions(); //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on //query execution when this filter is parsed to a FDO filter. switch (input.By) { case "OWNER": query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "ADDRESS": query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "BBOX": double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); if (parts.Length != 4) { throw new Exception("Invalid BBOX parameter"); } MgWktReaderWriter wktRw = new MgWktReaderWriter(); MgGeometry filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3])); query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects); break; default: throw new Exception("Unknown query type: " + input.By); } SearchResultViewModel vm = new SearchResultViewModel(); vm.Session = input.Session; vm.MapName = input.MapName; vm.LoadResults(layer, query); return View(vm); }
public ActionResult SelectFeature(SelectInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers[lidx]; MgClassDefinition clsDef = layer.GetClassDefinition(); MgPropertyDefinitionCollection props = clsDef.GetProperties(); MgPropertyDefinition idProp = props[0]; string idPropName = idProp.Name; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(idPropName + " = " + input.id); MgFeatureReader reader = layer.SelectFeatures(query); MgSelection selection = new MgSelection(map, ""); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); string result = ""; try { selection.Open(resSvc, input.MapName); selection.FromXml(""); //Clear existing selection.AddFeatures(layer, reader, 0); result = selection.ToXml(); } finally { reader.Close(); } return(Content(result, MgMimeType.Xml)); }
//--------------------------------------------------------------------------------------- // // ���ܣ�����ѯ���ת��ΪXML��ʽ���ַ� // // ���ߣ� // // ���ڣ� 2007.5.23 // // ����ʷ���� // //--------------------------------------------------------------------------------------- public void CreateSelectionXML(String queryString) { //������Դ��Ҫ�ط��� MgResourceService resService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); //��ȡҪ��ѯ��Ҫ��������ڵIJ� MgMap map = new MgMap(); map.Open(resService, "Sheboygan"); MgLayer layer = map.GetLayers().GetItem("Parcels"); //ִ��Ҫ�ز�ѯ MgResourceIdentifier resId = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureQueryOptions queryOption = new MgFeatureQueryOptions(); queryOption.SetFilter(queryString); MgFeatureReader featureReader = featureService.SelectFeatures(resId, "Parcels", queryOption); //����ѡ�� MgSelection selection = new MgSelection(map); selection.AddFeatures(layer, featureReader, 0); //����ѡ����ת��ΪXML OutputSelectionInHTML(selection, featureService); selectionXML = selection.ToXml(); }
public static string GetVisSelLayers(string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); StringBuilder sb = new StringBuilder(); sb.Append("({"); sb.Append("'layers': ["); foreach (var item in map.GetLayers()) { if (item.IsVisible() && item.Selectable) { sb.Append("{'name':"); sb.Append("'" + item.Name + "', "); sb.Append("'legend':"); sb.Append("'" + item.LegendLabel + "'"); sb.Append("},"); } } return sb.ToString().Substring(0, sb.ToString().Length - 1) + "]})"; }
public IActionResult SelectFeature(SelectInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers.GetItem(lidx); MgClassDefinition clsDef = layer.GetClassDefinition(); MgPropertyDefinitionCollection props = clsDef.GetProperties(); MgPropertyDefinition idProp = props.GetItem(0); string idPropName = idProp.Name; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(idPropName + " = " + input.id); MgFeatureReader reader = layer.SelectFeatures(query); MgSelection selection = new MgSelection(map, ""); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); string result = ""; try { selection.Open(resSvc, input.MapName); selection.FromXml(""); //Clear existing selection.AddFeatures(layer, reader, 0); result = selection.ToXml(); selection.Save(resSvc); } finally { reader.Close(); } return Content(result, MgMimeType.Xml); }
public static string GetVisSelLayers(string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); StringBuilder sb = new StringBuilder(); sb.Append("({"); sb.Append("'layers': ["); foreach (var item in map.GetLayers()) { if (item.IsVisible() && item.Selectable) { sb.Append("{'name':"); sb.Append("'" + item.Name + "', "); sb.Append("'legend':"); sb.Append("'" + item.LegendLabel + "'"); sb.Append("},"); } } return(sb.ToString().Substring(0, sb.ToString().Length - 1) + "]})"); }
string GetLegendInfo() { MgSiteConnection conn = new MgSiteConnection(); conn.Open(new MgUserInformation(sessionId)); MgResourceService resourceService = conn.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); map.Open(resourceService, mapName); List<LayerLegendInfo> infos = new List<LayerLegendInfo>(); foreach (MgLayer layer in map.GetLayers()) { if (layer.DisplayInLegend && layer.IsVisible() && !String.IsNullOrEmpty(layer.Name) && layer.LegendLabel != "MapOverview") { LayerLegendInfo layerInfo = GetLayerContent(resourceService, layer, Convert.ToDouble(scale)); if (layerInfo != null) infos.Add(layerInfo); } } System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string sJSON = oSerializer.Serialize(infos); return sJSON; //return string.Empty; }
private void BuildLayerTree(MgMap map) { System.Collections.Hashtable knownGroups = new System.Collections.Hashtable(); System.Collections.ArrayList unresolved = new System.Collections.ArrayList(); MgLayerGroupCollection groups = map.GetLayerGroups(); for (int i = 0; i < groups.GetCount(); i++) { MgLayerGroup rtGroup = groups.GetItem(i); Legend.TreeItem node = new Legend.TreeItem(rtGroup.GetName(), true, rtGroup, null); knownGroups.Add(node.name, node); MgLayerGroup parentGroup = rtGroup.GetGroup(); if (parentGroup == null) { this.tree.Add(node); } else { string parentName = parentGroup.GetName(); Legend.TreeItem parentNode = (Legend.TreeItem)knownGroups[parentName]; if (parentNode != null) { parentNode.Attach(node); } else { node.parentName = parentName; unresolved.Add(node); } } } if (unresolved.Count > 0) { for (int i = 0; i < unresolved.Count; i++) { Legend.TreeItem node = (Legend.TreeItem)unresolved[i]; Legend.TreeItem parentNode = (Legend.TreeItem)knownGroups[node.parentName]; if (parentNode != null) { parentNode.Attach(node); } else { this.tree.Add(node); } } } MgLayerCollection layers = map.GetLayers(); for (int i = 0; i < layers.GetCount(); i++) { if (layers.GetItem(i).GetDisplayInLegend()) { MgLayer rtLayer = (MgLayer)layers.GetItem(i); MgResourceIdentifier resId = rtLayer.GetLayerDefinition(); Legend.TreeItem node = new Legend.TreeItem(rtLayer.GetName(), false, rtLayer, this.resSrvc.GetResourceContent(resId).ToString()); MgLayerGroup parentGroup = rtLayer.GetGroup(); if (parentGroup == null) { this.tree.Add(node); } else { Legend.TreeItem parentNode = (Legend.TreeItem)knownGroups[parentGroup.GetName()]; if (parentNode != null) { parentNode.Attach(node); } else { this.tree.Add(node); } } } } }
private System.Collections.Hashtable BuildLayerMap(MgMap map) { System.Collections.Hashtable layerMap = new System.Collections.Hashtable(); MgLayerCollection layers = map.GetLayers(); for (int i = 0; i < layers.GetCount(); i++) { MgLayer rtLayer = (MgLayer)layers.GetItem(i); layerMap.Add(rtLayer.GetObjectId(), rtLayer); } return layerMap; }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string sessionId = GetRequestParameters(Request)["SESSION"]; string mapName = GetRequestParameters(Request)["MAPNAME"]; string locale = GetRequestParameters(Request)["LOCALE"]; if (string.IsNullOrEmpty(sessionId)) { Response.Clear(); Response.End(); return; } if (string.IsNullOrEmpty(mapName)) { Response.Clear(); Response.End(); return; } MgResourceService resourceSrvc = GetMgResurceService(sessionId); MgFeatureService featureSrvc = GetMgFeatureService(sessionId); MgMap map = new MgMap(); map.Open(resourceSrvc, mapName); string layernames = GetRequestParameters(Request)["LAYERNAMES"]; string GEOMETRY = GetRequestParameters(Request)["GEOMETRY"]; string selVar = GetRequestParameters(Request)["SELECTIONVARIANT"]; string type = GetRequestParameters(Request)["tp"]; string inputSel = GetRequestParameters(Request)["SELECTION"]; bool hasInputGeom = false; if (!string.IsNullOrEmpty(GEOMETRY)) { hasInputGeom = true; } //selection ima prednost pred podano geometrijo ... MgWktReaderWriter wktrw = new MgWktReaderWriter(); if (!string.IsNullOrEmpty(inputSel)) { MgGeometry inputGeom = MultiGeometryFromSelection(featureSrvc, map, inputSel); GEOMETRY = wktrw.Write(inputGeom); } MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); int nLayer = 0; // pobrišem in zgradim na novo samo tiste, ki imajo zadetke ... int nSloj = 0; string filter = ""; StringBuilder sbOut = new StringBuilder(); sbOut.Append("<table width=\"100%\" class=\"results\">"); sbOut.Append("<tr><td class='header'></td><td class='header'>" + "Layer" + "</td><td class='header' align=\"center\">" + "Select" + "</td><td class='header' align=\"center\">" + "Report" + "</td></tr>"); MgSelection selAll = new MgSelection(map); foreach (MgLayer layer in map.GetLayers()) { if (type != "2") { if (!layer.IsVisible()) { goto nextlay; } } if (layer.LegendLabel == "") { goto nextlay; } try { nLayer++; filter = String.Format("{0} {1} GeomFromText('{2}')", layer.GetFeatureGeometryName(), selVar, GEOMETRY); //preveriti še filter na Layerju. Ker ne gre drugače, je potrebno pogledati v XML MgResourceIdentifier layerDefResId = layer.GetLayerDefinition(); MgByteReader byteReader = resourceSrvc.GetResourceContent(layerDefResId); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); String xmlLayerDef = byteReader.ToString(); doc.LoadXml(xmlLayerDef); KALI.MGE.Objects.KALILayerDefinition.LayerDefinition ld = KALI.MGE.Objects.KALILayerDefinition.LayerDefinition.Parse(xmlLayerDef); if (!string.IsNullOrEmpty(ld.VectorLayerDefinition.Filter)) { filter += " AND (" + ld.VectorLayerDefinition.Filter + ")"; } //query the features MgFeatureQueryOptions opts = new MgFeatureQueryOptions(); opts.SetFilter(filter); String featureClassName = layer.GetFeatureClassName(); MgResourceIdentifier srcId = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(srcId, featureClassName, opts); bool hasResult = features.ReadNext(); if (hasResult) { nSloj++; int n = 0; MgClassDefinition classDef = features.GetClassDefinition(); MgPropertyDefinitionCollection classDefProps = classDef.GetIdentityProperties(); ArrayList idPropNames = new ArrayList(classDefProps.GetCount()); for (int j = 0; j < classDefProps.GetCount(); j++) { MgPropertyDefinition idProp = classDefProps.GetItem(j); idPropNames.Add(idProp.GetName()); } MgSelection sel = new MgSelection(map); do { // Generate XML to selection this feature MgPropertyCollection idProps = new MgPropertyCollection(); foreach (string id in idPropNames) { int idPropType = features.GetPropertyType(id); switch (idPropType) { case MgPropertyType.Int32: idProps.Add(new MgInt32Property(id, features.GetInt32(id))); break; case MgPropertyType.String: idProps.Add(new MgStringProperty(id, features.GetString(id))); break; case MgPropertyType.Int64: idProps.Add(new MgInt64Property(id, features.GetInt64(id))); break; case MgPropertyType.Double: idProps.Add(new MgDoubleProperty(id, features.GetDouble(id))); break; case MgPropertyType.Single: idProps.Add(new MgSingleProperty(id, features.GetSingle(id))); break; case MgPropertyType.DateTime: idProps.Add(new MgDateTimeProperty(id, features.GetDateTime(id))); break; default: //throw new SearchError(String.Format(MgLocalizer.GetString("SEARCHTYYPENOTSUP", locale), new Object[] { idPropType.ToString() }), searchError); break; } } sel.AddFeatureIds(layer, featureClassName, idProps); selAll.AddFeatureIds(layer, featureClassName, idProps); n++; //if (n > 1000) break; } while (features.ReadNext()); features.Close(); features.Dispose(); string selText = EscapeForHtml(sel.ToXml()); string seljs = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/></div>"; string seljs3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/></div>"; string linfo = "<b>" + layer.LegendLabel + "</b><br />" + n.ToString() + " " + "Hits"; sbOut.Append("<tr><td class=\"results\">" + nSloj.ToString() + "</td><td class=\"results\">" + linfo + "</td><td align=\"center\" class=\"results\">" + seljs + "</td><td align=\"center\" class=\"results\">" + seljs3 + "</td></tr>"); } } catch (Exception) { continue; } nextlay: continue; } sbOut.Append("</table>"); string selAllText = EscapeForHtml(selAll.ToXml()); string seljsAll = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/>" + "Select All" + "</div>"; string seljsAll3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/>" + "Report All" + "</div>"; sbOut.Append(string.Format("<br /><table width=\"100%\" class=\"results\"><tr><td class=\"results\">{0}</td><td class=\"results\">{1}</td></tr></table>", seljsAll, seljsAll3)); featureSrvc.Dispose(); resourceSrvc.Dispose(); if (nSloj > 0) { litPrebodi.Text = sbOut.ToString(); } else { litPrebodiTitle.Visible = false; litPrebodi.Text = "<b>" + "None layer lies below the selected item/area!" + "</b>"; } MgGeometry inGeom = wktrw.Read(GEOMETRY); double rw = map.ViewScale / Math.Sqrt(inGeom.Area); //koordinate if (hasInputGeom & rw > 400) { string output = ""; output = pointTransformAndWriteZ(GEOMETRY, map); litKoordinate.Text = output; litKoordinateTitle.Text = "Coordinates of selected points:"; } } }
private void ClearSessions() { try { InitializeWebTier(); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); MgLayerCollection layerCol = map.GetLayers(); string layerName = "LocationMarker"; MgLayer layerToRemove = null; foreach(MgLayer layer in layerCol) { if(layer.Name == layerName) { layerToRemove = layer; break; } } if(layerToRemove != null) { layerCol.Remove(layerToRemove); } map.Save(resourceService); Xcoord.Value = ""; Ycoord.Value = ""; kanam.Value = "10000"; targetsnewTitle.InnerHtml = ""; targetsnew.InnerHtml = ""; targetsold.InnerHtml=""; targetsoldTitle.InnerHtml = ""; Response.Write("<script>try{ parent.parent.mapFrame.Refresh(); parent.parent.mapFrame.ZoomToSelection();}catch(e){}</script>"); /* success = true;*/ } catch (Exception exx) { } }
public void CloseMarkup() { MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); // Add the Markup Layer MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "OPENMARKUP")); int index = map.GetLayers().IndexOf("_" + markupLayerResId.GetName()); map.GetLayers().RemoveAt(index); map.Save(resourceService); }
public Hashtable GetOpenMarkup() { Hashtable openMarkup = new Hashtable(); MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); MgLayerGroupCollection layerGroups = map.GetLayerGroups(); if (layerGroups.Contains("_Markup")) { MgLayerCollection layers = map.GetLayers(); for (int i = 0; i < layers.GetCount(); i++) { MgLayer layer = (MgLayer)layers.GetItem(i); if ((layer.GetGroup() != null) && (layer.GetGroup().GetName().Equals("_Markup"))) { openMarkup[libraryPath + layer.GetLegendLabel() + ".LayerDefinition"] = layer.GetLegendLabel(); } } } return openMarkup; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��Ӳ㵽���飬������鲻���ڣ��� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public MgLayer CreateLayerResource(MgResourceIdentifier layerResourceID, MgResourceService resourceService, string layerName, string layerLegendLabel, MgMap map) { MgLayer newLayer = new MgLayer(layerResourceID, resourceService); // �����㲢��Ӽҵ���ͼ�� newLayer.SetName(layerName); newLayer.SetVisible(true); newLayer.SetLegendLabel(layerLegendLabel); newLayer.SetDisplayInLegend(true); MgLayerCollection layerCollection = map.GetLayers(); if (!layerCollection.Contains(layerName)) { // ��Insert��������㣬�´����IJ�λ�ڻ��ƴ������� layerCollection.Insert(0, newLayer); } newLayer.SetDisplayInLegend(true); return newLayer; }
public string AddNaaz(double X, double Y, string MapSession, string mapName) { try { string dataSource = "Session:" + MapSession + "//RedlineSymbol.FeatureSource"; string layerDef = "Session:" + MapSession + "//RedlineSymbol.LayerDefinition"; // MgSiteConnection site = MGMapObject.GetMgSite(MapSession); MgUserInformation userInfo = new MgUserInformation(MapSession); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); // Create a ReserviceService object and use it to open the Map // object from the sessions repository. Use the Map object to // determine if the "AddressMarker" layer is visible. MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgMap map = new MgMap(); map.Open(resourceService, mapName); // MgLayer locationLayer = GetLayerByName(map, "LocationMarker"); if (siteConnection == null) { return "יש לרענן את האתר , לחיצה על כפתור הבית בפינה השמאלית עליונה"; } MgFeatureService featureSrvc = siteConnection.CreateService(2) as MgFeatureService; MgResourceService resourceSrvc = siteConnection.CreateService(0) as MgResourceService; MgResourceIdentifier dataSourceId = new MgResourceIdentifier(dataSource); MgResourceIdentifier layerDefId = new MgResourceIdentifier(layerDef); //MgMap map = MGMapObject.GetMgMap(resourceSrvc, mapName); MgGeometryFactory geomFactory = new MgGeometryFactory(); MgPoint geom = geomFactory.CreatePoint(geomFactory.CreateCoordinateXY(X, Y)); if (DataSourceExists(resourceSrvc, dataSourceId)) { resourceSrvc.DeleteResource(dataSourceId); } MgClassDefinition classDef = CreateFeatureClass("RedlineSymbol", "RedlineSymbol"); AddFeatureClassProperty(classDef, "KEY", 7, true); SetGeometryProp(classDef); MgFeatureSchema schema = CreateSchema(classDef, "RedlineSymbolShema", "RedlineSymbolShema"); MgCreateSdfParams parameters = new MgCreateSdfParams("ArbitraryXY", GetMapSrs(map), schema); featureSrvc.CreateFeatureSource(dataSourceId, parameters); MgLayerCollection layers = map.GetLayers(); MgLayer layer = FindLayer(layers, layerDef); LayerDefinitionFactory LayerDeffactory = new LayerDefinitionFactory(); if ((layer == null) && LayerDeffactory.CreateLayerDef("SymbolLayerDef_Cell", dataSource, "RedlineSymbol", "")) { resourceSrvc.SetResource(layerDefId, LayerDeffactory.layerDefContent, null); layer = new MgLayer(layerDefId, resourceSrvc); layer.SetDisplayInLegend(false); layer.SetSelectable(false); layer.SetVisible(true); layer.SetLegendLabel("ZoomSymbol"); layers.Insert(0, layer); } MgPropertyCollection featureProps = new MgPropertyCollection(); AddPointFeature("RedlineSymbol", featureProps, geom, featureSrvc, dataSourceId); if (layer != null) { layer.ForceRefresh(); } map.Save(resourceSrvc); siteConnection = null; map = null; dataSourceId = null; layerDefId = null; featureSrvc = null; resourceSrvc = null; geomFactory = null; geom = null; classDef = null; schema = null; featureProps = null; parameters = null; layers = null; layer = null; LayerDeffactory = null; GC.Collect(); GC.WaitForPendingFinalizers(); return "Ok"; } catch (Exception ex) { return ex.Message; } }
public string getPlanMapImageAsBase64String(string planID, string imageWidth, string imageHeight) { try { MgUserInformation userInfo = null; string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString(); MapGuideApi.MgInitializeWebTier(mapWebTierInit); // Om kartsession finns för applikationssession använd den annars skapa ny kartssitesession string mapSiteSessionID = null; if (Session["MapSiteSessionID"] != null) { mapSiteSessionID = Session["MapSiteSessionID"].ToString(); userInfo = new MgUserInformation(mapSiteSessionID); } else { // Initierar kartsite och kartsession string mapUserName = ConfigurationManager.AppSettings["MGUserName"].ToString(); string mapUserPass = ConfigurationManager.AppSettings["MGUserPass"].ToString(); userInfo = new MgUserInformation(mapUserName, mapUserPass); MgSite mapSite = new MgSite(); mapSite.Open(userInfo); userInfo.Dispose(); mapSiteSessionID = mapSite.CreateSession(); //mapSite.Close(); Session["MapSiteSessionID"] = mapSiteSessionID; userInfo = new MgUserInformation(mapSiteSessionID); } //bool test = resSvc.ResourceExists(mapResId); string mapSurfaceFactor = ConfigurationManager.AppSettings["MGMapSurfaceFactor"].ToString(); string mapRes = ConfigurationManager.AppSettings["MGMapResource"].ToString(); string planRes = ConfigurationManager.AppSettings["MGPlanytorResource"].ToString(); string planClassName = ConfigurationManager.AppSettings["MGPlanytorClassName"].ToString(); string planFilterColumn = ConfigurationManager.AppSettings["MGPlanytorFilterColumn"].ToString(); string planGeometryColumn = ConfigurationManager.AppSettings["MGPlanytorGeometryColumn"].ToString(); string planytorStrokeRgbaColor = ConfigurationManager.AppSettings["MGPlanytorStrokeRgbaColor"].ToString(); string planytorForegroundRgbaColor = ConfigurationManager.AppSettings["MGPlanytorForegroundRgbaColor"].ToString(); string mapImageSizeFromServer = ConfigurationManager.AppSettings["MGMapImageSizeFromServer"].ToString(); // Standardvärde för storlek på kartbild, används om värde ej finns i Settings.config eller skickas in som parametrar i webbmetod string mapImageWidthPixel = "400"; string mapImageHeightPixel = "300"; // Väljer bredd och höjd på kartbild om värde ska finnas i Settings.config samt indikeras att de ska användas // annars förväntas värde skickas med i webbmetod if (mapImageSizeFromServer.ToLower() == "true") { mapImageWidthPixel = ConfigurationManager.AppSettings["MGMapImageWidth"].ToString(); mapImageHeightPixel = ConfigurationManager.AppSettings["MGMapImageHeight"].ToString(); } else { if (!string.IsNullOrWhiteSpace(imageWidth) && !string.IsNullOrWhiteSpace(imageHeight)) { mapImageWidthPixel = imageWidth; mapImageHeightPixel = imageHeight; } } MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceService resSvc = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgResourceIdentifier mapResId = new MgResourceIdentifier(mapRes); MgFeatureService featSvc = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgResourceIdentifier planResId = new MgResourceIdentifier(planRes); // Filter för planDoc efter planDoc-ID MgFeatureQueryOptions featureQuery = new MgFeatureQueryOptions(); featureQuery.SetFilter(planFilterColumn + " = " + planID); MgFeatureReader featureReader = featSvc.SelectFeatures(planResId, planClassName, featureQuery); MgByteReader byteReaderGeometry = null; MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryCollection geometryCollection = new MgGeometryCollection(); int featureCount = 0; try { while (featureReader.ReadNext()) { byteReaderGeometry = featureReader.GetGeometry(planGeometryColumn); MgGeometry districtGeometry = agfReaderWriter.Read(byteReaderGeometry); geometryCollection.Add(districtGeometry); featureCount++; } } finally { featureReader.Close(); } MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgMultiGeometry multiGeometry = geometryFactory.CreateMultiGeometry(geometryCollection); MgMap map = new MgMap(siteConnection); MgEnvelope envelope = multiGeometry.Envelope(); // Anpassar ev. punkt till komma i tal som hanteras som textsträng för kommande konvertering if (mapImageHeightPixel.IndexOf(".") != -1) { mapImageHeightPixel = mapImageHeightPixel.Replace(".", ","); } if (mapImageWidthPixel.IndexOf(".") != -1) { mapImageWidthPixel = mapImageWidthPixel.Replace(".", ","); } // Önskad bilds höjd och bredd i punkter double imageHeightPixel = Convert.ToDouble(mapImageHeightPixel); double imageWidthPixel = Convert.ToDouble(mapImageWidthPixel); map.DisplayDpi = 120; double heightEnvelopeN = envelope.Height; double widthEnvelopeE = envelope.Width; // Anpassar utbredningen på sökta planer (envelope) till bildens format för att bevara skalriktighet string mapFarthest = string.Empty; if (heightEnvelopeN > widthEnvelopeE) mapFarthest = "height"; else mapFarthest = "width"; string imageFarthest = string.Empty; if (imageHeightPixel > imageWidthPixel) imageFarthest = "height"; else imageFarthest = "width"; double scale = 1.0; const double inch = 2.54; // Ändring av kartans utbredning och addering av utrymme i kartans bild runt planavgränsningen // Map = avgränsning enligt planytan (utbredning i kartan), Image = önskad bild att skapa med kartan // Om: kartans höjd är längst & bildens bredd är längst if (mapFarthest == "height" && imageFarthest == "width") { scale = imageWidthPixel / imageHeightPixel * inch; widthEnvelopeE = imageWidthPixel / imageHeightPixel * heightEnvelopeN * scale; } // Om: kartans bredd är längst & bildens höjd är längst else if (mapFarthest == "width" && imageFarthest == "height") { scale = imageHeightPixel / imageWidthPixel * inch; heightEnvelopeN = imageHeightPixel / imageWidthPixel * widthEnvelopeE * scale; } // Om: kartans höjd är längst & bildens höjd är längst else if (mapFarthest == "height" && imageFarthest == "height") { double compareSide = (heightEnvelopeN / (imageHeightPixel / imageWidthPixel)); bool isCompareSideFarthest = false; if (compareSide > widthEnvelopeE) { isCompareSideFarthest = true; } else { isCompareSideFarthest = false; } scale = imageHeightPixel / imageWidthPixel * inch; if (isCompareSideFarthest) { widthEnvelopeE = heightEnvelopeN / (imageHeightPixel / imageWidthPixel) * scale; } else { heightEnvelopeN = (imageHeightPixel / imageWidthPixel) * widthEnvelopeE * scale; } } // Om(annars): kartans bredd är längst & bildens bredd är längst else { double compareSide = (widthEnvelopeE / (imageWidthPixel / imageHeightPixel)); bool isCompareSideFarthest = false; if (compareSide > heightEnvelopeN) { isCompareSideFarthest = true; } else { isCompareSideFarthest = false; } scale = imageWidthPixel / imageHeightPixel * inch; if (isCompareSideFarthest) { heightEnvelopeN = widthEnvelopeE / (imageWidthPixel / imageHeightPixel) * scale; } else { widthEnvelopeE = heightEnvelopeN * (imageWidthPixel / imageHeightPixel) * scale; } } double mapSurfaceFactorDbl = Convert.ToDouble(mapSurfaceFactor.Replace('.', ',')); double newHeightN = heightEnvelopeN * mapSurfaceFactorDbl; double newWidthE = widthEnvelopeE * mapSurfaceFactorDbl; MgCoordinate lowerLeft = envelope.LowerLeftCoordinate; MgCoordinate upperRight = envelope.UpperRightCoordinate; envelope = new MgEnvelope(lowerLeft.X - (newWidthE - widthEnvelopeE) / 2, lowerLeft.Y - (newHeightN - heightEnvelopeN) / 2, upperRight.X + (newWidthE - widthEnvelopeE) / 2, upperRight.Y + (newHeightN - heightEnvelopeN) / 2); map.Create(resSvc, mapResId, mapResId.Name); // Skapa lagerdefinition i XML DefineAreaLayer areaLayer = new DefineAreaLayer(); areaLayer.FeatureName = planClassName; areaLayer.FeatureSourceName = planRes; areaLayer.GeometryColumnName = planGeometryColumn; areaLayer.Filter = planFilterColumn + " = " + planID; LayerScaleRangeCollection lsrCollection = new LayerScaleRangeCollection(); LayerScaleRange lsr = new LayerScaleRange(); // MinScale applikations-default till 0 (inklusive) om utelämnat, MaxScale applikations-default till kartans maxskala (exklusive) om utelämnat //lsr.MinScale = "0"; //lsr.MaxScale = "100000000"; AreaTypeStyle ats = new AreaTypeStyle(); AreaRuleCollection arCollection = new AreaRuleCollection(); AreaRule ar = new AreaRule(); //ar.Filter = planFilterColumn + " = " + planID; ar.LegendLabel = "Plan" + planID; AreaSymbolization2D symb2D = new AreaSymbolization2D(); Fill fill = new Fill(); fill.BackgroundColor = "FFFF0000"; fill.FillPattern = "Solid"; fill.ForegroundColor = convertRgbsToHexColor(planytorForegroundRgbaColor); Stroke stroke = new Stroke(); stroke.Color = convertRgbsToHexColor(planytorStrokeRgbaColor); stroke.LineStyle = "Solid"; stroke.Thickness = "1"; stroke.Unit = "Points"; symb2D.Fill = fill; symb2D.Stroke = stroke; ar.Symbolization2D = symb2D; arCollection.Add(ar); ats.AreaRules = arCollection; lsr.AreaTypeStyle = ats; lsrCollection.Add(lsr); areaLayer.LayerScaleRanges = lsrCollection; XmlDocument xmlFile = new XmlDocument(); //XDocument xmlFile = new XDocument(); // om returnerande av xml-dokument //xmlFile = areaLayer.CreateLayerDefinitionAsXmlDocument(); // om returnerande av xml-sträng xmlFile.LoadXml(areaLayer.CreateLayerDefinitionAsXmlString()); //xmlFile = areaLayer.CreateLayerDefinitionAsXDocument(); //xmlFile.Save(Server.MapPath(this.Context.Request.ApplicationPath) + "XmlTestLayerDefinition.xml"); using (MemoryStream msNewPlanLayer = new MemoryStream()) { xmlFile.Save(msNewPlanLayer); msNewPlanLayer.Position = 0L; //Note we do this to ensure our XML content is free of any BOM characters byte[] layerDefinition = msNewPlanLayer.ToArray(); Encoding utf8 = Encoding.UTF8; String layerDefStr = new String(utf8.GetChars(layerDefinition)); layerDefinition = new byte[layerDefStr.Length - 1]; int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0); // Save the new layer definition to the session repository MgByteSource byteSource = new MgByteSource(layerDefinition, layerDefinition.Length); MgResourceIdentifier layerResourceID = new MgResourceIdentifier("Session:" + mapSiteSessionID + "//" + "planytor" + ".LayerDefinition"); //"SearchedPlan" + planID + ".LayerDefinition"); resSvc.SetResource(layerResourceID, byteSource.GetReader(), null); MgLayer newPlanLayer = new MgLayer(layerResourceID, resSvc); newPlanLayer.SetName("Sökta planer"); newPlanLayer.SetVisible(true); newPlanLayer.SetLegendLabel("Sökta planer"); newPlanLayer.SetDisplayInLegend(true); MgLayerCollection layerCollection = map.GetLayers(); if (!layerCollection.Contains(newPlanLayer)) { // Insert the new layer at position 0 so it is at the top // of the drawing order layerCollection.Insert(0, newPlanLayer); } else { layerCollection.Remove(newPlanLayer); layerCollection.Insert(0, newPlanLayer); } map.Save(); } double mapScale = map.ViewScale; // XML-dokument till ren text //StringWriter stringWriter = new StringWriter(); //XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter); //xmlFile.WriteTo(xmlTextWriter); //xmlTextWriter.Flush(); string xmlSelection = string.Empty; //string xmlSelection = stringWriter.GetStringBuilder().ToString(); MgSelection selection = null; if (!string.IsNullOrEmpty(xmlSelection)) { selection = new MgSelection(map, xmlSelection); } else { selection = new MgSelection(map); } MgColor color = new MgColor("255,255,255"); // Skapar bild av kartan MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService); //MgByteReader byteReader = renderingService.RenderMap(map, selection, "PNG"); MgByteReader byteReader = renderingService.RenderMap(map, selection, envelope, Convert.ToInt32(imageWidthPixel), Convert.ToInt32(imageHeightPixel), color, "PNG"); MemoryStream ms = new MemoryStream(); byte[] byteBuffer = new byte[1024]; int numBytes = byteReader.Read(byteBuffer, 1024); while (numBytes > 0) { ms.Write(byteBuffer, 0, numBytes); numBytes = byteReader.Read(byteBuffer, 1024); } byte[] mapImageByte = ms.ToArray(); string imageBase64String = Convert.ToBase64String(mapImageByte); map.Dispose(); siteConnection.Dispose(); DataTable dtResult = new DataTable(); DataColumn dc = new DataColumn("MAPIMAGEBASE64"); dtResult.Columns.Add(dc); dc = new DataColumn("WIDTH"); dtResult.Columns.Add(dc); dc = new DataColumn("HEIGHT"); dtResult.Columns.Add(dc); DataRow dr = dtResult.NewRow(); dr["MAPIMAGEBASE64"] = imageBase64String; dr["WIDTH"] = imageWidthPixel; dr["HEIGHT"] = imageHeightPixel; dtResult.Rows.Add(dr); //TODO: MAP: Vad kan returneras, base64 eller länk där bild temporärt genereras på server //JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //return jsonSerializer.Serialize(imageBase64String); return getDatatableAsJson(dtResult); } catch (System.Exception ex) { UtilityException.LogException(ex, "Webbmetod : getPlanMapImageAsBase64String", true); return null; } }
//---------------------------------------------------------------------------------------- // �� �ܣ� ������ʱ�� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public bool CreatePointsLayer(String rootPath, String sessionId) { // ��ȡҪ�ط������Դ���� MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); // ��ͼ MgMap map = new MgMap(); map.Open(resourceService, "Sheboygan"); // ---Ҫ�����Ҫ�ز������û��������������滹Ҫ���ܣ�--��ʼ // ���������ݵ�Ҫ��Դ CreateFeatureSource(sessionId); String featureSourceName = "Session:" + sessionId + "//Points.FeatureSource"; MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName); MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection(); MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter(); MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); // �������¼ MgPropertyCollection propertyCollection = MakePoint("Point A", -87.727, 43.748); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point B", -87.728, 43.730); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point C", -87.726, 43.750); batchPropertyCollection.Add(propertyCollection); propertyCollection = MakePoint("Point D", -87.728, 43.750); batchPropertyCollection.Add(propertyCollection); // ��������Ҫ��������ӵ�Ҫ��Դ MgInsertFeatures Insertcmd = new MgInsertFeatures("Points", batchPropertyCollection); MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection(); featureCommandCollection.Add(Insertcmd); featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false); MgResourceIdentifier resourceID = null; //--------------Ҫ�����Ҫ�ز��� ���� // �����㣬ͨ���㹤��LayerDefinitionFactory LayerDefinitionFactory factory = new LayerDefinitionFactory(); factory.RootDirectoryPath = rootPath; //-------------------��������ʽ------------------------// // ������Ƿ���l string resourceSymbel = "Library://MgTutorial/Symbols/BasicSymbols.SymbolLibrary"; string symbolName = "PushPin"; string width = "24"; // unit = points string height = "24"; // unit = points string color = "FFFF0000"; string markSymbol = factory.CreateMarkSymbol(resourceSymbel, symbolName, width, height, color); // �����ı� string text = "ID"; string fontHeight = "12"; string foregroundColor = "FF000000"; string textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor); // ��������� string legendLabel = "trees"; string filter = ""; string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol); // ��������ʽ string pointTypeStyle = factory.CreatePointTypeStyle(pointRule); // �������ŷ�Χ string minScale = "0"; string maxScale = "1000000000000"; string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle); // �����㶨�� string featureName = "PointSchema:Points"; string geometry = "GEOM"; string layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange); MgByteSource byteSource = new MgByteSource(Encoding.UTF8.GetBytes(layerDefinition), layerDefinition.Length); MgByteReader byteReader = byteSource.GetReader(); resourceID = new MgResourceIdentifier("Session:" + sessionId + "//Points.LayerDefinition"); resourceService.SetResource(resourceID, byteReader, null); //��������IJ㶨�����ݣ������ã� MgByteSink byteSink = new MgByteSink(resourceService.GetResourceContent(resourceID)); string filePath = "C:\\Temp\\LayerDefinition.xml"; byteSink.ToFile(filePath); // �����㲢��ӵ�����͵�ͼ�� MgLayer newLayer = CreateLayerResource(resourceID, resourceService, "Points", "��ʱ��", map); AddLayerToGroup(newLayer, "Analysis", "����", map); MgLayerCollection layerCollection = map.GetLayers(); if (layerCollection.Contains("Points")) { MgLayer pointsLayer = layerCollection.GetItem("Points"); pointsLayer.SetVisible(true); } // �����ͼ map.Save(resourceService); return true; }
public void OpenMarkup() { MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); // Create the Layer Groups MgLayerGroup markupGroup = null; MgLayerGroupCollection layerGroups = map.GetLayerGroups(); if (layerGroups.Contains("_Markup")) { markupGroup = layerGroups.GetItem("_Markup"); } else { markupGroup = new MgLayerGroup("_Markup"); markupGroup.SetVisible(true); markupGroup.SetLegendLabel("Markup"); markupGroup.SetDisplayInLegend(false); layerGroups.Add(markupGroup); } // Add the Markup Layer MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "MARKUPLAYER")); MgLayer markupLayer = new MgLayer(markupLayerResId, resourceService); markupLayer.SetName("_" + markupLayerResId.GetName()); markupLayer.SetLegendLabel(markupLayerResId.GetName()); markupLayer.SetDisplayInLegend(false); markupLayer.SetSelectable(true); markupLayer.SetGroup(markupGroup); map.GetLayers().Insert(0, markupLayer); map.Save(resourceService); }
String GetLegendIcons() { // Initialize the web-tier. String realPath = Request.ServerVariables["APPL_PHYSICAL_PATH"]; String configPath = realPath + "..\\webconfig.ini"; MapGuideApi.MgInitializeWebTier(configPath); // Connect to the site. MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); // Get an instance of the required service(s). MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; // Get the current map. MgMap map = new MgMap(); map.Open(resourceService, mapName); // Get map layers. MgLayerCollection mgLayers = map.GetLayers(); // Define table-body rows, one per layer. int mgLayerCount = mgLayers.Count; // Get the current-visiable layer list String jsonlist = ""; for (int i = 0; i < mgLayerCount; i++) { MgLayer mgLayer = mgLayers.GetItem(i) as MgLayer; Boolean inLegend = false; String mgLayerName = mgLayer.LegendLabel; String mgLegendImage = mgLayer.GetLayerDefinition().Path + "/" + mgLayer.GetName(); String mgLayerIsVisible = mgLayer.IsVisible() ? "on" : "off"; String[] mgLayerData = new String[] { mgLegendImage, mgLayerName, mgLayerIsVisible }; for (int j = 0; j < mgLayerData.Length - 1; j++) { if (mgLayerData[mgLayerData.Length - 1] == "on" && mgLayerData[mgLayerData.Length - 2].Trim() != "") { jsonlist += mgLayerData[j] + "$"; inLegend = true; } } if (inLegend) jsonlist = jsonlist.Substring(0, (jsonlist.Length - 1)) + "@"; } return jsonlist.Substring(0, (jsonlist.Length - 1)); }
//--------------------------------------------------------------------------------------- // // ���ܣ�����һ����ΪtempParcel����ʱ�� // // ���ߣ� // // ���ڣ� 2007.5.23 // // ����ʷ���� // //--------------------------------------------------------------------------------------- public void createTempParcels(MgPolygon geom, ParcelProperty newParcel, string sessionId) { MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgResourceService resService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); // ��ȡ��ͼ���� MgMap map = new MgMap(); map.Open(resService, "Sheboygan"); // ������ʱ�� MgResourceIdentifier tempLayerSourceId = new MgResourceIdentifier("Session:" + sessionId + "//tempParcel.FeatureSource"); MgLayer tempParcelLayer = getLayerByName(map, "TempParcels"); if (tempParcelLayer == null) { createTempParcelFeatureSource(featureService, tempLayerSourceId); tempParcelLayer = createTempParcelLayer(resService, tempLayerSourceId, sessionId); map.GetLayers().Insert(0, tempParcelLayer); } //��Ҫ��Դ�в���Ҫ������ MgPropertyCollection props = populateParcelFeatureAttributes(geom, newParcel); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); commands.Add(new MgInsertFeatures("tempParcel", props)); featureService.UpdateFeatures(tempLayerSourceId, commands, false); tempParcelLayer.SetVisible(true); tempParcelLayer.ForceRefresh(); map.Save(resService); }
public String GetSelectionXML() { MgMap map = new MgMap(); map.Open(_resourceService, GetParameter(this.args, "MAPNAME")); MgLayerBase markupLayer = map.GetLayers().GetItem("_" + this.GetMarkupName()); MgSelection selection = new MgSelection(map); selection.AddFeatureIdInt32(markupLayer, markupLayer.FeatureClassName, Int32.Parse(GetParameter(this.args, "MARKUPFEATURE"))); return selection.ToXml(); }
public bool ShowSpatialFilter() { bool result = true; MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource"); MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService; MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection(); MgMap map = new MgMap(); map.Open(resourceService, Request["MAPNAME"]); MgLayer layer = null; MgLayerCollection layers = map.GetLayers(); if (layers.Contains("_QuerySpatialFilter")) { layer = (MgLayer)layers.GetItem("_QuerySpatialFilter"); //updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0")); } else { // Create the Feature Source (SDF) MgFeatureSchema sdfSchema = this.CreateFilterSchema(); MgCreateSdfParams sdfParams = new MgCreateSdfParams("MAPCS", map.GetMapSRS(), sdfSchema); featureService.CreateFeatureSource(sdfResId, sdfParams); // Create the Layer MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.LayerDefinition"); String layerDefinition = File.ReadAllText(GetQueryXmlTemplatePath()); layerDefinition = layerDefinition.Replace("%s", sdfResId.ToString()); MgByteReader reader = new MgByteReader(layerDefinition, "text/xml"); resourceService.SetResource(layerResId, reader, null); layer = new MgLayer(layerResId, resourceService); layer.SetName("_QuerySpatialFilter"); layer.SetLegendLabel("תחום זמני"); layer.SetDisplayInLegend(true); layer.SetSelectable(true); layer.ForceRefresh(); layer.NeedsRefresh(); layers.Insert(0, layer); } // Make the layer visible layer.SetVisible(true); map.Save(resourceService); // Add the geometry to the filter feature source MgPolygon polygon = this.CreatePolygonFromGeomText(Request["GEOMTEXT"].ToString()); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); MgByteReader byteReader = agfWriter.Write(polygon); MgPropertyCollection propertyValues = new MgPropertyCollection(); propertyValues.Add(new MgGeometryProperty("Geometry", byteReader)); try { updateCommands.Add(new MgInsertFeatures("Filter", propertyValues)); featureService.UpdateFeatures(sdfResId, updateCommands, false); } catch { } return result; }
protected void Button2_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(Xcoord.Value) || string.IsNullOrEmpty(Ycoord.Value) || string.IsNullOrEmpty(kanam.Value)) { // Response.Write("<script type='text/javascript'>try{ zoom();}catch(e){}</script>"); ClientScript.RegisterStartupScript(GetType(), "zoomme", "<script>try{ zoomzfd();}catch(e){}</script>"); return; } /* String mgSessionId = GetRequestParameters()["SESSION"]; String mgMap = GetRequestParameters()["map"]; //GeocodeAddress addr = null; bool success = false; decimal LatInput=0; decimal LonInput=0;*/ // Initialize the web-extensions and connect to the Site using // the session identifier passed in the query string. try { InitializeWebTier(); //MgUserInformation userInfo = new MgUserInformation(mgSessionId); // mgSessionId = site.CreateSession(); MgUserInformation userInfo = new MgUserInformation(mgSessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); decimal LatInput = System.Convert.ToDecimal(Xcoord.Value); decimal LonInput = System.Convert.ToDecimal(Ycoord.Value); /* LatInput = System.Convert.ToDecimal(GetRequestParameters()["LatInput"]); LonInput = System.Convert.ToDecimal(GetRequestParameters()["LonInput"]);*/ // Make the request to geocoder.us passing the address. //addr = requestGeocodeAddress(address); if (LatInput != 0 && LonInput != 0) { //Request the specified address to the geocode service using REST, the // GET interface // if (targetsnew.InnerHtml == "") { targetsnewTitle.InnerHtml = "מיקום נוכחי :"; targetsoldTitle.InnerHtml = ""; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } else { targetsoldTitle.InnerHtml = "מיקום קודם :"; targetsold.InnerHtml += targetsnew.InnerHtml; targetsnew.InnerHtml = "<table>"; targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">"; targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\"> מיקום נמצא </a></td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>"; targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>"; targetsnew.InnerHtml += "</table>"; } // The geocode successfully returned a location. //if (IsDebugAssembly(this.GetType().Assembly)) // System.Diagnostics.Debugger.Launch(); MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); MgMap map = new MgMap(); map.Open(resourceService, mgMap); // map.Open(mgMap); // Check the map for the AddressMarker layer. If it does not // exist then create a feature source to store address results // and a layer to display them. MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Session:" + mgSessionId + "//LocationMarker.FeatureSource"); // Session:7f4231a2-0d7e-11e2-8000-000c294ca3a6_en_7F0000010AFC0AFB0AFA//a2f5e4fb-0c3c-4ee7-bb5d-c8f4a226a68b.FeatureSource // MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Library://rany1/Data/findLocation/temp/LocationMarker.FeatureSource"); // string layerDef = "Session:" + mgSessionId + "//LocationMarker.FeatureSource"; //string dataSource = "Library://rany1/Data/LocationMarker.FeatureSource"; /*string layerDef = "Library://rany1/Layers/LocationMarker.LayerDefinition"; MgLayerCollection colLays = map.GetLayers(); MgLayer layer = FindLayer(colLays, layerDef);*/ //// MgLayer locationLayer = FindLayerByName(,"LocationMarker") ;//GetLayerByName(map, "LocationMarker"); //MgLayerCollection colLays = map.GetLayers(); MgLayerCollection colLays = map.GetLayers(); MgLayer locationLayer = FindLayerByName(colLays, "LocationMarker"); if (locationLayer == null) { // diverr.InnerHtml += " לא נמצאו שכבות LocationMarker "; lf.CreateLocationMarkerFeatureSource(featureService, locationMarkerDataResId, map); locationLayer = lf.CreateLocationMarkerLayer(resourceService, locationMarkerDataResId, mgSessionId); map.GetLayers().Insert(0, locationLayer); } else if (locationLayer.GetVisible()) { // If the layer exists and is visible, then display the // previous results. //EmitAddressResults(featureService, locationMarkerDataResId, mgSessionId, Response); EmitLocationResults(featureService, locationMarkerDataResId, mgSessionId, HttpContext.Current.Response); } // Insert the results of the Geo-Code into the temporary // feature source and ensure the address marker layer // is visible. MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter(); MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgPoint locationPoint = geometryFactory.CreatePoint(geometryFactory.CreateCoordinateXY(Convert.ToDouble(LonInput), Convert.ToDouble(LatInput))); MgPropertyCollection properties = new MgPropertyCollection(); properties.Add(new MgStringProperty("Address", "")); properties.Add(new MgGeometryProperty("Location", geometryReaderWriter.Write(locationPoint))); MgFeatureCommandCollection commands = new MgFeatureCommandCollection(); commands.Add(new MgInsertFeatures("LocationMarker", properties)); featureService.UpdateFeatures(locationMarkerDataResId, commands, false); locationLayer.SetVisible(true); locationLayer.ForceRefresh(); map.Save(resourceService); Response.Write("<script type='text/javascript'>try{ parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); /* success = true;*/ } else { // Response.Write("<tr><td>נקודת הציון לא נמצאה: <hr></td></tr>"); } } catch (MgException eee) { // Response.Write("<script type='text/javascript'>try{alert('rany'); parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>"); // Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); // Response.Write("<tr><td>" + eee.InnerException.Message + "</td></tr>"); Response.Write("<tr><td>" + eee.ToString() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetBaseException() + "</td></tr>"); Response.Write("<tr><td>" + eee.GetStackTrace()+ "</td></tr>"); Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>"); Response.Write("<tr><td class=\"Spacer\"></td></tr>"); // Response.Write("<tr><td>" + eee.GetDetails() + "</td></tr>"); } }